diff --git a/.gitignore b/.gitignore index c9e0aca55ea..67d798efd45 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 65db556fabd..02d0bc12e2e 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 diff --git a/build.gradle b/build.gradle index 1ca1d522724..bf5df93e859 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,8 @@ 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:docbook-reference-plugin:0.2.4") + classpath("org.springframework.build.gradle:propdeps-plugin:0.0.3") + classpath("org.springframework.build.gradle:docbook-reference-plugin:0.2.6") } } @@ -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" @@ -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" @@ -60,7 +58,7 @@ configure(allprojects) { project -> test { systemProperty("java.awt.headless", "true") - systemProperty("testGroups", properties.get("testGroups")) + systemProperty("testGroups", project.properties.get("testGroups")) } repositories { @@ -71,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", "spring-orm", + 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"]) { @@ -235,7 +233,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 { @@ -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")) @@ -587,7 +587,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 @@ -598,7 +597,8 @@ project("spring-webmvc-tiles3") { description = "Spring Framework Tiles3 Integration" merge.into = project(":spring-webmvc") dependencies { - compile(project(":spring-context")) + 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") @@ -613,11 +613,13 @@ 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" } provided("javax.servlet:javax.servlet-api:3.0.1") - compile(project(":spring-web").sourceSets*.output) // mock request & response testCompile("org.slf4j:slf4j-jcl:${slf4jVersion}") } } @@ -641,10 +643,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", "**/*TestSuite.class"]) + } + dependencies { compile(project(":spring-core")) optional(project(":spring-beans")) @@ -676,7 +690,7 @@ project("spring-test-mvc") { merge.into = project(":spring-test") dependencies { optional(project(":spring-context")) - compile(project(":spring-webmvc")) + 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") @@ -753,6 +767,7 @@ configure(rootProject) { apply plugin: "docbook-reference" apply plugin: "groovy" + apply plugin: "detect-split-packages" apply from: "${gradleScriptDir}/jdiff.gradle" reference { @@ -760,12 +775,15 @@ configure(rootProject) { pdfFilename = "spring-framework-reference.pdf" } - // don"t publish the default jar for the root project + detectSplitPackages { + projectsToScan -= project(":spring-instrument-tomcat") + } + + // don't publish the default jar for the root project configurations.archives.artifacts.clear() 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")) @@ -790,10 +808,16 @@ 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 options.overview = "src/api/overview.html" + options.stylesheetFile = file("src/api/stylesheet.css") options.splitIndex = true options.links(project.ext.javadocLinks) @@ -801,18 +825,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) { @@ -954,6 +980,7 @@ configure(rootProject) { "set GRADLE_OPTS=$gradleBatOpts %GRADLE_OPTS%\nset DEFAULT_JVM_OPTS=") } } + } /* 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 00000000000..ddafa956ef7 --- /dev/null +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy @@ -0,0 +1,158 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS 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/MergePlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy index 097e65ab93c..4143780702b 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 @@ -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) } 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 e57b04dec22..1d6134ab597 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 { 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 00000000000..10b1e4e981d --- /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 diff --git a/gradle/ide.gradle b/gradle/ide.gradle index e1bb117641e..3f73282254a 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,76 @@ 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+"/bin/eclipse") +eclipse.classpath.file.beforeMerged { classpath -> + classpath.entries.findAll{ it instanceof SourceFolder }.each { + if(it.output.startsWith("bin/")) { + it.output = null + } + } +} +eclipse.classpath.file.whenMerged { classpath -> + classpath.entries.findAll{ it instanceof SourceFolder }.each { + it.output = "bin/" + 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/') + outputs.upToDateWhen { false } +} + +task eclipseWstComponent(type: Copy) { + from rootProject.files( + "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("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) +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("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-false-build") +} diff --git a/gradle/publish-maven.gradle b/gradle/publish-maven.gradle index 528e78c15d5..d47098b4f12 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 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 7e101ea57d6..e14f2546121 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 3463e8cc613..0fe05596793 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 b9863ab67ad..65e296f594c 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/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java index dbfcbd380e3..271d961088b 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; } /** 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 0dd176354eb..31fdb83f7d8 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/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java b/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java index 9e6baee9327..5d76f6c8a5e 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; } 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 06010d6710e..d66adc843cc 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/interceptor/AsyncExecutionAspectSupport.java b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java index 96237b86d17..7fbfbf56044 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 792639b1c6f..daa23a32936 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-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java b/spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java index c27d1872cff..a695d98e4c0 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/AspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java index cf96bf3f06b..b042d8155a2 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 @@ -309,13 +309,9 @@ 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 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 ac6dc31a2a2..057ad77309f 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 8c84e801b8d..0e0e4377c9a 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; @@ -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/TigerAspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java index b8c336b0fbb..bc9f1b4f626 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); @@ -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/aspectj/TypePatternClassFilterTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java index fea874179e0..0275360441b 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 ae3ac04918e..d0009394a13 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. @@ -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 test.beans.ITestBean; -import test.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(); @@ -399,7 +404,6 @@ public abstract class AbstractAspectJAdvisorFactoryTests { } } - @SuppressWarnings("unchecked") @Test public void testIntroductionOnTargetExcludedByTypePattern() { LinkedList target = new LinkedList(); @@ -442,7 +446,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()); @@ -650,7 +654,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; @@ -936,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 { @@ -979,7 +983,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 d15b0a11cab..66d5e0f739e 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 88beb1455a5..966d289eb13 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 93aebbfa673..16d6f0e9e79 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 6b7d3ff0965..f1ff305aad4 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/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java index 08d95808edc..96313821a35 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 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 939493b2eb0..984f5ada7b8 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 0d86588b8c9..fec13dbbed1 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 472b91f7183..cd01ffd5326 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 7654895ccee..850fbc15d1b 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 19ea1742c0b..7320dd553cc 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 3dbd38f98c6..9e0b3d14ebb 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 dca823663df..bfd5a35c079 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 @@ -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/IntroductionBenchmarkTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/IntroductionBenchmarkTests.java index 03b971fed02..eaaf2d8d42b 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 4e815534441..139ef6c415e 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 7f5a4bc4376..3c373cdb77a 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; @@ -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/framework/ProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java index ddf48d28d82..7f856028885 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 fe72f963255..e13097c4b68 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 @@ -142,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-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java index 964fac9efaf..db2751f5137 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/CustomizableTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java index 77aad8e9ff1..0c1c50c9c52 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/ExposeBeanNameAdvisorsTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java index 170f5b34bc5..3b0bd31e530 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 bea92760ce6..5f00163fb55 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 632c5bad07d..5a0cc658c93 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 @@ -45,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/aop/interceptor/SimpleTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java index 6efc651d272..96501f2c14f 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-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java index ccbe9502bfa..84c4decb198 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 b230ed72605..03cf0b719e3 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 505697408c9..01be11617ea 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 42992fb57c2..51f18dde21f 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 1c250e966da..35828d28e0b 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 2ca2acd665e..513885ed21f 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 6288f7674af..be21c52d2aa 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 1b7c8d60b36..7a7257ea2f3 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,11 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +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; @@ -27,16 +31,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 @@ -156,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-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java b/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java index 5b3ceb039b8..8f06791335c 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 8b89281e763..5edde823dbc 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 1ed7cd8430a..b24dccc2c9d 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 1e3ae07f26a..cbd660d7fe9 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 b55f2bb9f90..4a3d04cbd8f 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 75be80560ee..07e9e4d3d95 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 e70d2c7baa3..af6b44c0ca1 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 04cc623d30b..33f30be78c1 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 cb897b602f1..a4bb0c2554b 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 9bfe5dfd960..f633c66d5b2 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 74b1fe0ec22..10ef6a35aef 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 57cedd275bc..b5bb4a1751c 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 ea2eef2ae13..91e1d087f59 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 b271b1f5565..961269efde2 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 1a6d5be3e30..b8976f1958a 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 a8a3a01e3a3..2b37761fabc 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; @@ -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/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 91a49faa0fe..2e34d50262c 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 e0e45d6f142..931b0ec6681 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 abe79f9dc32..cb2d10d6ab6 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; @@ -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-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 bdcb2f2c9e4..0fa9d4b4da9 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 b1cdf832a4a..d152719261c 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 d8d179f7e43..8c72878c9df 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 eb9789edb37..de4dfecff6b 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 7c66f4b451b..38e0903e2e6 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 dbe365f4937..2730d50c8ec 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 b18646f4d02..45546b4cfde 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/annotation/EmptySpringAnnotation.java b/spring-aop/src/test/java/test/annotation/EmptySpringAnnotation.java index 60c43c858ff..140f0fee3d4 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 039b06e8a7d..e62a4e2ff32 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/MethodCounter.java b/spring-aop/src/test/java/test/aop/MethodCounter.java deleted file mode 100644 index ae673bd168d..00000000000 --- 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 20b9ece08fd..00000000000 --- 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/PerTargetAspect.java b/spring-aop/src/test/java/test/aop/PerTargetAspect.java index 3896f2dc7ab..7c8c1fec83d 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/SerializableNopInterceptor.java b/spring-aop/src/test/java/test/aop/SerializableNopInterceptor.java deleted file mode 100644 index 064df39ab52..00000000000 --- 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/aop/TwoAdviceAspect.java b/spring-aop/src/test/java/test/aop/TwoAdviceAspect.java index 42ee4bf0ca3..6745457a9d2 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-aop/src/test/java/test/beans/Colour.java b/spring-aop/src/test/java/test/beans/Colour.java deleted file mode 100644 index 8793fd3f94b..00000000000 --- 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 225ae1a300d..00000000000 --- 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 56c9d829ee3..00000000000 --- 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/ITestBean.java b/spring-aop/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 74f371b0547..00000000000 --- 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 edc145ad7d2..00000000000 --- 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 974d7d9b772..00000000000 --- 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/TestBean.java b/spring-aop/src/test/java/test/beans/TestBean.java deleted file mode 100644 index 3f50f93836c..00000000000 --- 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 5aa69c1fa89..00000000000 --- 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 e9bc9fee04a..00000000000 --- 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 4fedb8998b0..00000000000 --- 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/aspects.gradle b/spring-aspects/aspects.gradle index 0432414467b..81728303163 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) @@ -30,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 { @@ -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) 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 760cea9dc1e..033a083016d 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. 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 390e1dc989c..fa8fc6441f3 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. @@ -17,6 +17,7 @@ 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 @@ -51,6 +52,7 @@ public abstract aspect AbstractDependencyInjectionAspect { * 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()); 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 5cd0140d464..8270d6962d5 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. @@ -41,9 +41,9 @@ import java.io.Serializable; * 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, + * {@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. + *
  • 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 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 5313df9ed16..2f1e91ccd23 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. @@ -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; @@ -77,6 +78,7 @@ 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()); /* 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 351c11d7d9e..b4a3d93d1d3 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. @@ -41,7 +41,7 @@ package org.springframework.beans.factory.aspectj; * @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+); 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 a9a6da82e98..ce68942d405 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. 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 be3957a3a08..5418488b532 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/context/annotation/aspectj/SpringConfiguredConfiguration.java b/spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java index 51347810dd0..8534fd76b5a 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/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj index e373607d558..972a3248593 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. @@ -106,7 +106,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth * 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 } 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 1c50c64bbe6..816f6a1e424 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. 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 3594725aaee..131c82beefd 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,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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 { + } + 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 a64def7ed11..660b35c1361 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. 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 ed0956ef9fe..f9c70661ae1 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. @@ -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(); - TransactionInfo txInfo = 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 1fe8de9030b..70a82b5f4ee 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. @@ -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/aop/aspectj/autoproxy/CodeStyleAspect.aj b/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj index 0758d3a403a..77da43176ab 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-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 a992a2ebfc6..00000000000 --- 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 a10846ba95a..00000000000 --- 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 d7fb346185a..00000000000 --- 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 478999c05da..00000000000 --- 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 d7af36ed641..00000000000 --- 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 88b450b9171..00000000000 --- 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 ac8e5ea4857..00000000000 --- 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 73f37a8f9eb..71a10afcaf1 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; @@ -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); } @@ -304,7 +305,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { // } // } - + @SuppressWarnings("unused") private static class ShouldNotBeConfiguredBySpring { private String name; @@ -335,6 +336,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable + @SuppressWarnings("unused") private static class ShouldBeConfiguredBySpringUsingTypeNameAsBeanName { private String name; @@ -350,6 +352,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable(autowire=Autowire.BY_TYPE) + @SuppressWarnings("unused") private static class ShouldBeConfiguredBySpringUsingAutowireByType { private TestBean friend = null; @@ -365,6 +368,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable(autowire=Autowire.BY_NAME) + @SuppressWarnings("unused") private static class ValidAutowireByName { private TestBean friend = null; @@ -380,6 +384,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 +398,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { } } - + @SuppressWarnings("unused") private static class ArbitraryExistingPojo { private TestBean friend; @@ -426,6 +431,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable + @SuppressWarnings("unused") private static class BaseBean { public int setterCount; @@ -447,7 +453,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { } @Configurable - @SuppressWarnings("serial") + @SuppressWarnings({"serial", "unused"}) private static class BaseSerializableBean implements Serializable { public int setterCount; @@ -467,6 +473,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Aspect + @SuppressWarnings("unused") private static class WireArbitraryExistingPojo extends AbstractBeanConfigurerAspect { @Pointcut("initialization(ArbitraryExistingPojo.new(..)) && this(beanInstance)") @@ -477,6 +484,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-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 1c678ba6b19..aae9ff6cd75 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/beans/factory/aspectj/beanConfigurerTests-beans.xml b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/beanConfigurerTests-beans.xml index 89aa3964eae..bd6439bb546 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 3771a21b9f7..00000000000 --- 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 53% 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 df237674754..c85d84d0833 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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/AnnotatedClassCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java index 52a1b4265e1..b8108051798 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) { } @@ -135,4 +140,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 81dd758d19d..98c1da1e031 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); @@ -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-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java index 95edbcd9d64..d29d43894e0 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. @@ -27,89 +27,113 @@ import org.springframework.cache.annotation.Caching; * Simple cacheable service * * @author Costin Leau + * @author Phillip Webb */ 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", unless = "#result > 10") + public Long unless(int arg) { + return (long) arg; + } + + @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 +141,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/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java index b95ee6b8078..d82367ddb07 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++; 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 969cf90a8fb..00000000000 --- 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 6af0f02db37..0d08cdcb56f 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 be562b2585b..b69e861933a 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. @@ -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.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; +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-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index bac8df4ce6d..df5def12a8d 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/CachedIntrospectionResults.java b/spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java index 47ff208dd4e..7c8cd51cece 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/main/java/org/springframework/beans/ExtendedBeanInfo.java b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java index c3609c10c22..6606741ee4e 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-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java b/spring-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java index 1e074dcc338..8ab240836bf 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 2efc1edf737..6d69a63ce69 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 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 fb107425c36..f993f1f7135 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/BeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 2d18e67b1ac..8c73a16fd7a 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 2a4f577a1c0..657bb1ebd1d 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 0157d086506..5bd8ea7a9f1 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 00000000000..7db0bae6e12 --- /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/access/BeanFactoryReference.java b/spring-beans/src/main/java/org/springframework/beans/factory/access/BeanFactoryReference.java index 35c3d3f51fa..c2c0a7c6294 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-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 e1f0e2f3921..6775dd78edc 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 74a5e59d240..62f62dccd9e 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 862dbd6fa6a..4e945234860 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 03e5716fdd7..a9b29f96571 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 7477e197cb8..b23c93e97fd 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 836098ff8cd..e9e5e60a7a5 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/config/ServiceLocatorFactoryBean.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java index e8f2b72b6c7..1ded4154aa2 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-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 c112676ea1d..09faf0c3b25 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. @@ -572,28 +572,30 @@ 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); + 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 processedType = ibp.predictBeanType(beanClass, beanName); - if (processedType != null) { - return processedType; + Class predicted = ibp.predictBeanType(targetType, beanName); + if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) || + FactoryBean.class.isAssignableFrom(predicted))) { + return predicted; } } } } - return beanClass; + return targetType; } /** @@ -610,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(); @@ -685,7 +687,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. 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 8db728ae579..9e97ba2fafa 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; } @@ -746,6 +749,9 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { + if (result == null) { + return null; + } result = resolver.resolveStringValue(result); } return result; @@ -1329,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/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java index 6a2cb27e495..5b9b571f80f 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 161eae7e99b..384866ffdd7 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 824caaaec5e..bffe7e764fc 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; @@ -89,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 @@ -270,12 +272,28 @@ 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) { + 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) { return getParentBeanFactory().getBean(requiredType); } else { - throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found " + - beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new NoSuchBeanDefinitionException(requiredType); } } @@ -718,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)) { @@ -733,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) { @@ -823,8 +841,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 +912,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/DisposableBeanAdapter.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java index 990438597f6..6a498344a92 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-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 7b7822f0df0..d51dc55fa72 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-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 7eaba17a546..64d0555d491 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. */ 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 80a6b345198..4eef1b4751f 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-2012 the original author or authors. + * Copyright 2002-2013 the original author 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/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java b/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java index e46145f2968..81fa4242b2f 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 @@ -47,7 +46,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()); @@ -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-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 37ef1b40904..ffe9d294d9b 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 9900aa16517..a422d5b4fcd 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; 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 07bfe7afa93..3bd9e1d85e9 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 a7ca4fbd54e..4110ed0a220 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-beans/src/test/java/com/foo/Component.java b/spring-beans/src/test/java/com/foo/Component.java deleted file mode 100644 index 5c5d61ec81c..00000000000 --- a/spring-beans/src/test/java/com/foo/Component.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.foo; - -import java.util.ArrayList; -import java.util.List; - -public class Component { - private String name; - private List components = new ArrayList(); - - // mmm, there is no setter method for the 'components' - public void addComponent(Component component) { - this.components.add(component); - } - - public List getComponents() { - return components; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/spring-beans/src/test/java/com/foo/ComponentNamespaceHandler.java b/spring-beans/src/test/java/com/foo/ComponentNamespaceHandler.java deleted file mode 100644 index b29eeca0614..00000000000 --- a/spring-beans/src/test/java/com/foo/ComponentNamespaceHandler.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.foo; - -import org.springframework.beans.factory.xml.NamespaceHandlerSupport; - -public class ComponentNamespaceHandler extends NamespaceHandlerSupport { - @Override - public void init() { - registerBeanDefinitionParser("component", - new ComponentBeanDefinitionParser()); - } -} 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 f49f63182cf..b35e6aabf75 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}. @@ -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/BeanWrapperAutoGrowingTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java index 73bdeaee1c6..06a7eb86ac1 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-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java index 3946cccb25e..8c7d8da1e89 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 a1752458c42..3a9e03accc0 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 @@ -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)); @@ -497,6 +496,7 @@ public class BeanWrapperGenericsTests { } + @SuppressWarnings("unused") private static class NestedGenericCollectionBean extends BaseGenericCollectionBean { private Map mapOfInteger; @@ -544,6 +544,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 29e282c0a27..9ec9af033b8 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 @@ -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/CachedIntrospectionResultsTests.java b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java index 4675d22dbff..618ced2e496 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. @@ -18,13 +18,12 @@ 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 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.*; @@ -37,14 +36,14 @@ 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")); 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); @@ -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 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 95c3fbb8cc9..2d98f138bae 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/ExtendedBeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java index d1c21b1b3ac..30b2013d072 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. @@ -28,9 +28,9 @@ import java.math.BigDecimal; 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; @@ -193,7 +193,6 @@ public class ExtendedBeanInfoTests { } } class Child extends Parent { - @Override public Integer getProperty1() { return 2; } @@ -215,7 +214,6 @@ public class ExtendedBeanInfoTests { @Test public void cornerSpr9453() throws IntrospectionException { final class Bean implements Spr9453> { - @Override public Class getProp() { return null; } @@ -605,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; } } @@ -879,7 +875,6 @@ public class ExtendedBeanInfoTests { } interface TextBookOperations extends BookOperations { - @Override TextBook getBook(); } @@ -889,7 +884,6 @@ public class ExtendedBeanInfoTests { } class LawLibrary extends Library implements TextBookOperations { - @Override public LawBook getBook() { return null; } } @@ -904,7 +898,6 @@ public class ExtendedBeanInfoTests { } class B extends A { - @Override public boolean isTargetMethod() { return false; } @@ -981,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/BeanFactoryUtilsTests-leaf.xml b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-leaf.xml index bf756e1bbc5..71586ad8d36 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 2d124050745..c5fa5b28581 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 ff33aa02125..28f8d652776 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 d05f7ba577d..553f9cef46d 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 aae1e1073a1..27d839a8913 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 @@ -41,7 +41,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import static org.junit.Assert.*; -import static test.util.TestResourceUtils.*; +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 0e474fadaed..94f6376ce18 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,24 @@ 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; +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 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; import java.net.MalformedURLException; @@ -32,19 +50,15 @@ 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.Rule; 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.junit.rules.ExpectedException; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.NotWritablePropertyException; @@ -70,20 +84,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.*; +import org.springframework.util.StringValueResolver; /** * Tests properties population and autowire behavior. @@ -93,11 +112,14 @@ import static org.junit.Assert.*; * @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() { @@ -569,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 @@ -1261,6 +1282,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); @@ -1270,6 +1297,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(); @@ -1287,7 +1340,8 @@ public class DefaultListableBeanFactoryTests { try { lbf.getBean(TestBean.class); fail("Should have thrown NoSuchBeanDefinitionException"); - } catch (NoSuchBeanDefinitionException ex) { + } + catch (NoSuchBeanDefinitionException ex) { // expected } } @@ -2145,7 +2199,6 @@ public class DefaultListableBeanFactoryTests { doTestFieldSettingWithInstantiationAwarePostProcessor(true); } - @SuppressWarnings("unchecked") private void doTestFieldSettingWithInstantiationAwarePostProcessor(final boolean skipPropertyPopulation) { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); @@ -2212,6 +2265,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 { } @@ -2259,6 +2332,7 @@ public class DefaultListableBeanFactoryTests { this.spouse = spouse; } + @SuppressWarnings("unused") private ConstructorDependency(TestBean spouse, TestBean otherSpouse) { throw new IllegalArgumentException("Should never be called"); } @@ -2485,6 +2559,7 @@ public class DefaultListableBeanFactoryTests { /** * Bean with a dependency on a {@link FactoryBean}. */ + @SuppressWarnings("unused") private static class FactoryBeanDependentBean { private FactoryBean factoryBean; @@ -2571,6 +2646,7 @@ public class DefaultListableBeanFactoryTests { } + @SuppressWarnings("unused") private static class TestSecuredBean { private String userName; @@ -2600,29 +2676,7 @@ 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; - } - - } - + @SuppressWarnings("unused") 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 bccb33a9781..62c85b60b2b 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 c5f365f7997..e422accf4b7 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 5acfcca8b6f..7181f0b8a12 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 f9295e4ee61..4fbb7b8cb1d 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 4cfba96615d..a18a25e05ae 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 c5c49d9b3bd..252ee0ddb80 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/CustomScopeConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java index 65e6debd15f..f06388cc8d7 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/FieldRetrievingFactoryBeanTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests-context.xml index b9c8625b2f8..2e2d9fd435f 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 d5569c3fd3c..66226340aa4 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 a7faf0cc085..dc56161776d 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 409e3f8325d..cc43afb4da0 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 b33b3c9c65a..490aab87909 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 6ec0c706e64..ce21ee90954 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 c0c65711bc2..63e49fb18bf 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 ab67af35a3a..fab64afdcb5 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. @@ -17,12 +17,13 @@ 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; 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 +49,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: @@ -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/config/SimpleScopeTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests-context.xml index f6f4f4a0a23..1c1978456ca 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 861cafa68d2..0a561dd3360 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 d0c52278445..c2cc486e9da 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 82a35dc064f..550e87375b2 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,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.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rob Harrop @@ -78,7 +77,6 @@ public final class CustomProblemReporterTests { @Override public void error(Problem problem) { - System.out.println(problem); this.errors.add(problem); } @@ -88,13 +86,8 @@ public final class CustomProblemReporterTests { @Override public void warning(Problem problem) { - 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/BeanDefinitionBuilderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java index 365ae6b9581..48bd97d15b1 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 c761254fdae..11aed3fa64c 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 655a5a0e0fa..2480f64fac2 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,10 +47,11 @@ import org.springframework.core.io.UrlResource; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import test.beans.GenericBean; -import test.beans.GenericIntegerBean; -import test.beans.GenericSetOfIntegerBean; -import test.beans.TestBean; +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 2e4025d304a..f9f1beba04a 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 51e8dd70122..d62e43d0601 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/QualifierAnnotationAutowireBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java index 195ad775290..cb7cf5580ba 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/Spr8954Tests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java index 5c1368c4610..411f5380451 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-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 6c9d11f210a..3e9a6577b55 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/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index 65e380d3e2e..d0439fa93ef 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. @@ -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. @@ -75,6 +71,7 @@ public class CallbacksSecurityTests { private DefaultListableBeanFactory beanFactory; private SecurityContextProvider provider; + @SuppressWarnings("unused") private static class NonPrivilegedBean { private String expectedName; @@ -117,6 +114,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedSpringCallbacksBean implements InitializingBean, DisposableBean, BeanClassLoaderAware, BeanFactoryAware, BeanNameAware { @@ -161,6 +159,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedFactoryBean implements SmartFactoryBean { private String expectedName; @@ -204,6 +203,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedFactory { private final String expectedName; @@ -452,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(); @@ -511,8 +508,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/support/security/support/ConstructorBean.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/support/ConstructorBean.java index 0b65929fdd3..a68028c5921 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); } } 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 ded4bb5eaef..625e8c7085e 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 490d0a7e1bf..3d88251b7e1 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 @@ -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()); } @@ -336,32 +337,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 6a04c540743..4c1ac580bb9 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 9cc414ee651..ae6232f40ff 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 72de2d65d11..a9294e05fd1 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 f57b78d2591..3a88ab9fa8f 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 6a31f91e1a3..082fc418b0e 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 75bcc94d84b..7b02d0bed29 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 d1449fdb0b7..a0d4f722e15 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 b897d98858a..8e53cee2934 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 e8bf2b4469a..12a2fb08602 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 58c392ddcaa..bd92b0c3916 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 62f4e654b65..ff691358a44 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 696ab6c0afe..0d67448bc05 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 1623cf3ac52..ba8c74bfe96 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 @@ -61,6 +62,7 @@ public class FactoryMethods { return new FactoryMethods(tb, null, num); } + @SuppressWarnings("unused") private static List listInstance() { return Collections.EMPTY_LIST; } @@ -98,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/factory/xml/InstanceFactory.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/InstanceFactory.java index 25ab86c6416..6c8872054e1 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 a6feaedcec6..5b9ddc18e66 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 8344d0b5298..17552b1d591 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 f9416028884..601afa44fbe 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 badce0656bd..45e89564e72 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 438a4b7e9e3..849da031cc3 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 d042952a88e..3bb04d4c593 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 18f616eb14d..6960653ea6e 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 76baf7366fe..c5da99f0e4c 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 5b6e88a1555..2fd60f7a0e0 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/CustomCollectionEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java index 14b3f4d48d0..4f9463a5c71 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 ca477008cd2..af590e3936b 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()); } /* @@ -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/PagedListHolderTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java index 481466d4281..7e7694767c6 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,9 +24,9 @@ import org.junit.Test; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import static org.junit.Assert.*; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; +import static org.junit.Assert.*; /** * @author Juergen Hoeller 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 320759d1b8a..ad1666fcd11 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-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 94% 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 1924dac82e6..b581a05f032 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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 org.springframework.beans.factory.xml; +package org.springframework.tests.beans; import java.util.ArrayList; import java.util.Collection; @@ -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-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 4ea2f67d3bb..92484b7d1aa 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 a992a2ebfc6..a4a7d9740b4 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 50657647656..e5f6947de5a 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-core/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-core/src/test/java/org/springframework/beans/CustomEnum.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/CustomEnum.java index 1e43492191b..66a863772ff 100644 --- a/spring-core/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 8bed2eeeab0..b17d1028cc5 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 c0f63181aba..91416208a2b 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 a8428c7f780..cb5767eef59 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 60f7966d9a0..dc08778c536 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 12ff808dc84..c192382a1b7 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 43b6465df08..b7465b1bfa1 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 93% 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 021c0cd1c16..a0fee60195d 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 73fe70276e2..4639050b2a6 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 e0ae5f20a3f..58c4b9d502d 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 f3c6263261e..694f32d2759 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 526c3dacfb5..b467348a93d 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 bd2a72662f6..d319bbd0eda 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 cd1dcd6e5e0..1a81d10340a 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 959861e6b47..cc83d69d833 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 edc145ad7d2..844c5ea6921 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 cdd80bd27b2..489c9335091 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 eeb4b7325db..142a5da2d26 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 eb78f612fb0..61563f0dd8a 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 621ecbc3a2c..9477a5e5488 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 c050b64856c..cb276da9cbd 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 f9c4f273826..b562f569fa0 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 00000000000..575bd1933f9 --- /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 9ae4f54ec24..00000000000 --- 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 533d0df36e3..00000000000 --- 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/INestedTestBean.java b/spring-beans/src/test/java/test/beans/INestedTestBean.java deleted file mode 100644 index 56c9d829ee3..00000000000 --- 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 9397b175503..00000000000 --- 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 5b94f078b5d..00000000000 --- 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 4843151231b..00000000000 --- 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/log4j.xml b/spring-beans/src/test/resources/log4j.xml index 37f573d2aef..6f012e99240 100644 --- a/spring-beans/src/test/resources/log4j.xml +++ b/spring-beans/src/test/resources/log4j.xml @@ -11,21 +11,13 @@ - - - - - - - - - + - + 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 5beaf6d5982..8d5f74fc31a 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 c33326c8574..4d3723c7de8 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 be6700e1423..d0f1eea3266 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 12dbc607928..2edadb511eb 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 6363230a06c..2fcb1179545 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 3f32de8aee3..a2e966aab98 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 e32686f27f7..9b93a16810d 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 2883bd2383a..089517cd427 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 22168ca8c8c..7e262a0a0d4 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 a614172a897..d8fc1db88ea 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 44bd0b92dc9..974ae6c3d9c 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 7cd04cc145a..8a31ff86962 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 f97701759b6..4ff20b3d591 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 33cbb8dd8d6..7802a4c935b 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 f245c964dd0..d9616443011 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 7c10f7a32f6..1773a1c9c61 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 e44a8c961c5..8dd70708d3d 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 d82595bac7a..384171fdc03 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 9d1d1f7adb8..933e66b7d00 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 8426c5d95ee..25f20439fa2 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 fab962d4dde..3cca869dbff 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 324fb483ff4..20aa0f53740 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 7cb0723a4c2..05c47afa53a 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/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java index fc2ad000222..dcec4047eee 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 1fc70da9055..a94c1fe2cb1 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-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,21 +31,24 @@ 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} + * {@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 @@ -54,6 +60,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; @@ -66,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) */ @@ -77,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() @@ -88,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) { @@ -97,22 +107,43 @@ 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)); + 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+ + 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); - } } @@ -130,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(); } 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 47a115e9805..4184b2f3b41 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()) { 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 84db22173a5..ed8baa41dff 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-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java b/spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java index 574c7695e7f..027f0f4a6bc 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); } 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 ddb091770ee..00000000000 --- 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 412891c439b..00000000000 --- 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 6d71de75764..00000000000 --- 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/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java index 646a6797171..6e8efcd8165 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(); @@ -132,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); @@ -144,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()); 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 a95a2408b54..00000000000 --- 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 79c1dfba7f7..ca55ed9a0e1 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 @@ -52,7 +52,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; @@ -64,7 +65,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/main/java/org/springframework/cache/annotation/CachePut.java b/spring-context/src/main/java/org/springframework/cache/annotation/CachePut.java index 0cc7f883f19..3ab2f52b0a0 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 716b840ad0e..1ab8df5762f 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/Caching.java b/spring-context/src/main/java/org/springframework/cache/annotation/Caching.java index 7d3e77d3192..6bad879b76f 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/cache/annotation/SpringCacheAnnotationParser.java b/spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java index 9114dfc6332..d8c7575ce7e 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 a1206c576f7..5092f474c73 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 7c62a21af7a..8e0b36889d1 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,13 +486,19 @@ 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; } } -} \ No newline at end of file +} 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 62186d89661..f671c84f759 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 cd8a40ceb2c..46d84590e8e 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 edb84ba156b..e6a61b0adfb 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 23c0b20e2c8..f9375a9a54e 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 2ee38bb8728..ba109397a22 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) { @@ -89,4 +124,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 c8c3e27905b..7dc1289a41a 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/cache/support/AbstractCacheManager.java b/spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java index 5d301d85f4c..29a5a98973b 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()); 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 91b82e2825d..5b741d60694 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/AnnotationScopeMetadataResolver.java b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java index f678425ea84..6a7db8bd313 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-context/src/main/java/org/springframework/context/annotation/Bean.java b/spring-context/src/main/java/org/springframework/context/annotation/Bean.java index a0c8ab11593..679352decf1 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; 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 a105e147f79..93a71336a0f 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/Configuration.java b/spring-context/src/main/java/org/springframework/context/annotation/Configuration.java index b09623c29c0..ec3cf117ef7 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 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 e41aca17280..e1676c6eb2c 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; 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 99678159d33..37c74ce2a1f 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); 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 2901e5cea0d..c03aca61ddf 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)); } } + } 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 a4cf352a2b7..effcec5df91 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 da58779fd87..648a8e92113 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 c7ad16ac501..3a70e3c5f06 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/event/SimpleApplicationEventMulticaster.java b/spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java index 2e13855d4a5..71e4ec53694 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/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java b/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java index 138f45526cd..66aff5979be 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); } 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 8dc2c1ffb3e..605aa72e871 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/main/java/org/springframework/context/support/ResourceBundleMessageSource.java b/spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java index eeca86a1080..8d711989d97 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 ce39ce9a6cd..29de41bc3ed 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/ejb/interceptor/SpringBeanAutowiringInterceptor.java b/spring-context/src/main/java/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.java index 89d50674517..33c15966306 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); } 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 eb413a6ea7a..b74b53262b5 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. @@ -40,24 +40,28 @@ 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(dateFormatter); - registry.addFormatterForFieldType(Calendar.class, 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) { - Assert.notNull(dateFormatter,"DateFormatter must not be null"); + Assert.notNull(dateFormatter, "DateFormatter must not be null"); this.dateFormatter = dateFormatter; } @@ -117,7 +121,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/JodaTimeConverters.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java index 6943ad4241f..b49b6072559 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/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java index 51d9f9684b1..7ad1a4e62e6 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); } /** @@ -174,19 +174,28 @@ 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()); } 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) { 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 345131a5aa4..7c5fceaed58 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 2dc19dda744..25d20688dde 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 86907d33ddc..14d1beeb8a6 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 e35bd31fcb7..4405dc3fdc5 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 a128608d84d..8ae2481ea52 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 8325e1b7982..2ba16e0f8e7 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 75c250078f3..a0a911e8bda 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 723a947e1ab..b1300d699b1 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 dce57618981..5b56adf42ca 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 1e71d0cdbbf..54211b00d60 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 03b49e13260..e925e5bfc38 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 aede3544be8..5967740664e 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 6662830c73a..a4e38db93d3 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 f313e65fbc3..95f1d07b5fb 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/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java index d38e5be9483..f953d9465cf 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 320a64790e1..b75e956dab9 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/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java b/spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java index 74b0a3f3c04..38339d4b7f7 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); } /** 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 8660e2cf5be..caa7f51452a 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() + "]"; 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 ba9d8775d99..fb8e9032755 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 dcd5f91f85b..81bf07e825c 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/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java index a9abadab855..542aa15e322 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 873740c21c7..35e57c59d20 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/main/java/org/springframework/scheduling/annotation/Scheduled.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java index dea788ce088..383e4adc5de 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 f5f236d2f9d..754afc5bd67 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/concurrent/ExecutorConfigurationSupport.java b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java index 964872e1d6e..91764b33286 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(); + } + } } } 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 19cd880bbb7..3e04248ea86 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 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 00000000000..8a0fba8c3ba --- /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 redirects the actual scheduling + * of tasks to the {@link ContextRefreshedEvent} callback. Falls back to regular + * {@code 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/IntervalTask.java b/spring-context/src/main/java/org/springframework/scheduling/config/IntervalTask.java index 4b39927e8f7..567f9fdbfe1 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/config/ScheduledTaskRegistrar.java b/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java index 592fd033c13..2efd26cea9e 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 a892eb414b1..8f6963614f4 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 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 b3530ebf785..68d127c72f3 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,8 +69,21 @@ public class CronSequenceGenerator { private final TimeZone timeZone; + /** - * 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 @@ -81,6 +94,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 @@ -112,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(); } @@ -135,7 +154,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 +163,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 +173,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 +182,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 +204,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 +245,8 @@ public class CronSequenceGenerator { } } - // Parsing logic invoked by the constructor. + + // Parsing logic invoked by the constructor /** * Parse the given pattern expression. @@ -230,8 +254,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 +320,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 +348,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/main/java/org/springframework/scheduling/support/CronTrigger.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java index eca37982e6d..94f6385a1a9 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-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java b/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java index b494e4c5ff0..e25fdd3f254 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/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java index 23cfe64423f..f12e4004bf7 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/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java b/spring-context/src/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java index 97b9a3bc43d..3d019c22fec 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 23be717eacd..c0de42493f4 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-context/src/main/java/org/springframework/validation/DataBinder.java b/spring-context/src/main/java/org/springframework/validation/DataBinder.java index a9d5d835873..35e0ea4a568 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()); + } } } 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 58cd161175b..3d4b907fa2f 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 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 1a51c37bb9b..f3c45fc2fa2 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,10 @@ 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 (!"".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); } String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field); 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 9bfdf140102..baf1f802c0a 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/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 91b49de3275..56680707c22 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 34b479d12cb..eb23e55017b 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 @@ ]]> + + + + + + + + + + + + + + + + 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 ac7c3174183..e6288503896 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 574fb05b432..5a34213de74 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 edce1324f4d..54ae90e9e12 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 34e9775fe24..5bd66ded436 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 @@ diff --git a/spring-context/src/test/java/example/scannable/FooServiceImpl.java b/spring-context/src/test/java/example/scannable/FooServiceImpl.java index 1db44f5bb0b..15da02b0f2d 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/aop/aspectj/AfterAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java index 0e9f634bd43..364d5415920 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 9a55cc823e3..66d0e85228a 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 a2f1054e9e4..c04a54f8e64 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 197afbf0695..97c02b34523 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 e57c4df2172..07605079249 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 9152fe1853e..77dd0c36247 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 67195904dc8..879e846b2bd 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 91ca7c6540c..2198e32f49c 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 7f947101837..e00fa847a7d 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 5b606689acd..585d1806950 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 6dae894ae62..038614eccf4 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 b88de9c97db..2b363cab83b 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 8a23b5ad4d5..9ec75d75aab 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 e43cc579883..4ab6a830646 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 987a8b852cf..b446755d57b 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 53a81f6e5a7..7c225060489 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 66ccb584951..42dafc3e90d 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 4df2dc36337..94e6e43f8ab 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 d12031f34eb..4aac362c73e 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 059aae0b0f6..c2948de1ab1 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 @@ -20,8 +20,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; import org.springframework.tests.Assume; 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 d8b4887fe66..fc449b6943c 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 0e7435362af..f9d810c6262 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 01bd862dd1b..c88962cd533 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 1c10ec952fe..6a4a56e7f01 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 3268b8ccecc..f8ca001d0de 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 57f3f9dd4d7..94725cb5e31 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 7d846604000..6490decb219 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 361809558b4..9b6a0b61740 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 f609c08b3e7..7ca3e87e15a 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 3eedc35b006..da15419d113 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 8a399d03618..2b23fab3029 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 c1c8376b305..88907c1b6c4 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 a299f40e300..53c2a50c662 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 e02baf027b8..efb221722a0 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 408c5477395..25f545b5425 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 a916c5a1e51..e00377721c4 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 047ef0daafe..9505a844d7f 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 c6da3d6ea83..16293b388e0 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 44bc1872f6a..462d8bcdc65 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 e26835163f3..2306641f0e5 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 d585ce96211..b35902d133f 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 0c6b68d805f..b5c5b065d5f 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 8b0975e8a93..759e4c89447 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 d6c4cccceec..453d22ccaf2 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 a988324a003..c750e8ae574 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 24ce7bcf1fe..ea160ca1130 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 1761a3552e4..7abc4287b71 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 68681cf9fbd..a68195265dc 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 2a83b2078a5..f2b1e064721 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 88cad34d9aa..4e098059b53 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 38f9d7b6201..855bda381c5 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 417512a71ef..3632c978038 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 1f84e8edac2..9df36d7a387 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 3fe28a8663d..c9238290990 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 90ead2afe56..5fc378d78f6 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 09d3dacd844..4896d143b26 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 73ed03922c3..1ddb6b9a005 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 85080527360..051d281260e 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 0ca26dd9534..b1327c8bdb1 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 51b63bd7d6c..b9e0a9eaaeb 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,28 @@ 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.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; +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 @@ -163,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"); 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 d600115868a..2330909eecc 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; /** @@ -136,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/aop/framework/JdkDynamicProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java index 911e4d51542..77101f6cc90 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 27e7988a7a7..3cda6a7921a 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 8c0a313a7c3..7675fe6e0e4 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 795cea64182..dde1f91017d 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 45a4c2707b7..d0f5a89896c 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 92faa57c4fc..e59244c49cb 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 de65fec0fe1..fd46c5552fd 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 92ef595c55c..47cd14f94d4 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 f437df5edf0..291385ce50a 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 4131b85d785..396bfada125 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 4e9ab797adc..07f2825c1fc 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 1efb2ae3053..036dac321fa 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 b6e0f6853e8..f55c1a41b30 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 0aa3b46d648..a58e040b67d 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 36718003309..69bd476f3b2 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 57e8de81126..e708c9f1791 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 286f8c840dd..c64c7e6ef74 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 83598caf9b8..bf1fc8b5a78 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 4019d568d0c..d9a838ee2ab 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 53d945697e8..d53272f0d58 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 11805c6d5bb..49216292485 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 0f4b265b721..c9727ea856e 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 c0a695c452c..5ec8db261f8 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/BeanWithObjectProperty.java b/spring-context/src/test/java/org/springframework/beans/BeanWithObjectProperty.java deleted file mode 100644 index bb5e71f5cd0..00000000000 --- a/spring-context/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-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 a992a2ebfc6..00000000000 --- 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 c5360de5316..00000000000 --- 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 61f911902c7..00000000000 --- 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 9f90cf15bb1..00000000000 --- 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 412891c439b..00000000000 --- 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 7c66f4b451b..00000000000 --- 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 dbe365f4937..00000000000 --- 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 d6911ee72f5..00000000000 --- 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 855f23af396..00000000000 --- 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 013a65a0e49..00000000000 --- 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 4b4d6980564..00000000000 --- 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 f54299a03f9..00000000000 --- 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 2dde7a31b37..00000000000 --- 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 d42adc1daf3..00000000000 --- 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/support/InjectAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java index d7cf863defa..3544595d9dc 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/DependenciesBean.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java deleted file mode 100644 index 28c3bffa8f4..00000000000 --- 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 017af485203..9eaf910d083 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 ed9fbbde83b..96e2ab404a9 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/QualifierAnnotationTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java index 91d1d7565ad..5271e479157 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/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java index b1e6c818f0d..c21ee9078fb 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 98f04505649..a5bc212cedb 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; @@ -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/beans/factory/xml/XmlBeanFactoryTests-autowire.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-autowire.xml index 4fcad300bab..43510574bae 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 654e76e7fb5..fc90f7905c7 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 9a735571d89..7729dbc7882 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 85eb3620b0f..8370424f739 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 bc4f87d63a4..d500c48881e 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 ea061046ce3..d703fddd21f 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 0094234b090..3815538559d 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 5021766b1c0..3451c1b37c0 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 feb3bea4994..10ae8ae09fb 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 f94371ee0c7..86da8d595d4 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 1a6eb553328..06281490175 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 e8b85a509af..cd232df3c00 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 da6d7405eb3..2e49f71a540 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 bf0849bc98c..0a92c7426d0 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 98f23096735..f575bcb44a9 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 c8adc19bb3d..f8e32809066 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 3386242887d..9eb0813411a 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 e5515885eff..31fa7a16bab 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 4b315b7582d..daa269998ee 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 8c1d0d3f37c..65fbd833c9f 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 92981195029..9088b962e0f 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 cc049ed23cd..393028d4f1f 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 e991af7167a..90de5444371 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 19faed79258..a771266aa9a 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 df21ad72626..8cd2e725690 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 f18e9e77c29..a96c4d303d8 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 8463f132a12..4968b12b3a6 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 3eed0d7cfc1..6115b4979e7 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; @@ -133,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); @@ -157,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); @@ -172,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); @@ -235,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); @@ -268,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); @@ -295,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); @@ -310,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); @@ -324,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); @@ -338,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); @@ -357,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); @@ -375,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); @@ -389,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(); @@ -414,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); @@ -432,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); @@ -450,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); @@ -471,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); @@ -485,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"); @@ -495,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); @@ -504,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); @@ -521,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); @@ -531,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); @@ -542,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); @@ -557,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); @@ -572,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); @@ -592,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"); @@ -600,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"); @@ -617,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); @@ -629,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"); @@ -640,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 { @@ -654,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 { @@ -672,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); @@ -692,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); @@ -709,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); @@ -724,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); @@ -734,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); @@ -744,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); @@ -755,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); @@ -766,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"); @@ -774,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); @@ -792,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"); @@ -801,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); @@ -809,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(); @@ -870,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); @@ -892,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"); @@ -929,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); @@ -958,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); @@ -972,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"); @@ -1020,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"); @@ -1035,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 { @@ -1053,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 { @@ -1064,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); } @@ -1131,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 @@ -1146,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); @@ -1154,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" @@ -1177,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" @@ -1186,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)); @@ -1196,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)); @@ -1206,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); @@ -1219,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); @@ -1284,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); @@ -1331,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); @@ -1354,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 { @@ -1371,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(); @@ -1394,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); @@ -1403,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); @@ -1414,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); @@ -1427,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"); @@ -1435,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"); @@ -1443,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"); @@ -1473,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"); @@ -1489,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"); @@ -1498,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"); @@ -1507,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"); @@ -1516,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"); @@ -1525,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"); @@ -1533,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"); @@ -1543,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); @@ -1554,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); @@ -1565,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); @@ -1574,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); 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 1fbd8330863..17c9c7e8f5b 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 7a52f76eda2..68accbae1d4 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/cache/config/AbstractAnnotationTests.java b/spring-context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java index 4bc0c888b31..41d717d6927 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 4c72d9d5937..f168ab990ad 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 81dd758d19d..98c1da1e031 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 f9f19b47594..f987d7bbe61 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/ExpressionEvaluatorTests.java similarity index 61% 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 b52f364746a..44762719bcf 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 @@ -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; -public class ExpressionEvalutatorTest { +/** + * @author Costin Leau + * @author Phillip Webb + */ +public class ExpressionEvaluatorTests { + + @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/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java index a7207435209..6f407fb24e0 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 69fea0435db..96f39c3296a 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 30b7c590c89..81770ea423f 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 6f5675fffd6..99d732a1642 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 e87e6023780..8001716e485 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 bfbc2c9ef65..e3ed03301f4 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/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index 23973400039..f53c9e1a253 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,27 +122,28 @@ 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()))); } } - @SuppressWarnings("unchecked") @Test public void getBeanByTypeAmbiguityRaisesException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TwoTestBeanConfig.class); 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") ) 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 d35b5396fd3..578748f4fd2 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. @@ -17,15 +17,14 @@ package org.springframework.context.annotation; import static org.junit.Assert.*; -import static org.junit.Assume.assumeFalse; 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/BeanMethodPolymorphismTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java index 4797aae61be..1d573540f8a 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({ "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/ClassPathBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java index 50b8cd20459..55d08669d09 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 1e4deb22f08..4475d87e4a8 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 62aa1411a3a..e2c1cc3b57d 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.*; @@ -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/ComponentScanAnnotationIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java index 7b461584a0a..f6d90975c2d 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/ComponentScanParserBeanDefinitionDefaultsTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java index 28fdcccca0a..bf0baeaa53c 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/ComponentScanParserScopedProxyTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java index 4cbfd9b34e7..31a87271caf 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 ee826eb33a0..b35fc045745 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 eb288746fd2..6972adada9a 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 d52a9db656f..815c487294d 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/ConfigurationClassSpr8954Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassSpr8954Tests.java new file mode 100644 index 00000000000..1a7a5b1b33e --- /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; + } + } + +} 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 7baf82681eb..87999283a31 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; + } + } + } 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 c01fc14cec5..eab6f37b7fe 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 44fc77e3b5e..1b95433a63e 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 b23695db3ba..e895a207c3a 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 49007b8a348..52aaaac7e91 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 125c77c6363..6c59cf85228 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 b2cc55fec21..fcfe98d94ad 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 8dbb67f34ae..42098c96e79 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 56233a73730..d124bac8306 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 592337551c2..1a0e064b757 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 3384916c081..17176f9dcd6 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 4dda9faf6c6..152cf5d758d 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 8c39e53d32e..152ecfb6ecd 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 e339891102f..6c959877127 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 717148bc4c2..232374bd0ed 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 38939c7fcb5..7ff83e35eae 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 49fda87dab2..396e4a1bb0c 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; @@ -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/context/support/EnvironmentSecurityManagerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java new file mode 100644 index 00000000000..42647392832 --- /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-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java index 39482f71cfc..24185526d6c 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 3e640d91457..078b1169790 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/ResourceBundleMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java index 7e45ce98985..c0121a4a2dd 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) { 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 e03b30eaa68..887c6fc1cc1 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 39651c9370f..b1f9d24ecd6 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 acddae3ff11..bba7f776685 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 8a94e8326e4..908f5652c12 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 57c2b5c8af0..bcfae1cdb55 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 5e407ee0be0..5ddcbab67d4 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 1eab846bc5e..6b9c028005b 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/access/SimpleRemoteSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java index c0fa18c2c33..0c03c57c69d 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-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java index d8c1aa13902..4eea7e81555 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 1afb7000f3c..c2430271b43 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 6d1a3ddf833..e8767251a95 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/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 087e8e95214..2803f0dc9f9 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. @@ -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; @@ -30,10 +33,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; @@ -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(); @@ -186,6 +192,49 @@ public class DateFormattingTests { assertEquals("10/31/09", binder.getBindingResult().getFieldValue("children[0].dateAnnotated")); } + @Test + 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 597a3820b50..c2aaf8d36a3 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. @@ -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,20 +37,19 @@ 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; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.format.annotation.DateTimeFormat; 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 + * @author Phillip Webb */ public class JodaTimeFormattingTests { @@ -456,6 +460,41 @@ public class JodaTimeFormattingTests { assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("mutableDateTimeAnnotated")); } + @Test + 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 { 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 ae9aa8be0e8..284b238e56d 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 6b0fb87da7e..417ded1a459 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 b2efa269c1e..7907a518719 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/jmx/AbstractMBeanServerTests.java b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java index 12dbf05a50c..ab05a3ea6ed 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,32 +20,38 @@ 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.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 * @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 +70,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/JmxTestBean.java b/spring-context/src/test/java/org/springframework/jmx/JmxTestBean.java index d42fbf201b3..b1a773128df 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/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index 7842ee328cb..e1bd521a1df 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,18 +29,23 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; +import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.jmx.IJmxTestBean; 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 * @author Juergen Hoeller * @author Sam Brannen + * @author Chris Beams */ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { @@ -78,6 +83,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { return (IJmxTestBean) factory.getObject(); } + @Test public void testProxyClassIsDifferent() throws Exception { if (!runTests) return; @@ -85,6 +91,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; @@ -95,6 +102,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; @@ -103,6 +111,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The age should be 100", 100, age); } + @Test public void testSetAttributeValue() throws Exception { if (!runTests) return; @@ -111,6 +120,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; @@ -123,6 +133,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetAttributeValueWithCheckedException() throws Exception { if (!runTests) return; @@ -135,6 +146,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetAttributeValueWithIOException() throws Exception { if (!runTests) return; @@ -147,6 +159,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetReadOnlyAttribute() throws Exception { if (!runTests) return; @@ -159,6 +172,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testInvokeNoArgs() throws Exception { if (!runTests) return; @@ -167,6 +181,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The operation should return 1", 1, result); } + @Test public void testInvokeArgs() throws Exception { if (!runTests) return; @@ -175,6 +190,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The operation should return 3", 3, result); } + @Test public void testInvokeUnexposedMethodWithException() throws Exception { if (!runTests) return; @@ -187,19 +203,13 @@ 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 { + @Test + public void testTestLazyConnectionToRemote() throws Exception { 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/RemoteMBeanClientInterceptorTestsIgnore.java b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java similarity index 75% 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 7082efec132..74a29b0be01 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,14 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; /** * @author Rob Harrop + * @author Chris Beams */ -// 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"; @@ -48,6 +43,9 @@ public class RemoteMBeanClientInterceptorTestsIgnore extends MBeanClientIntercep @Override public void onSetUp() throws Exception { + runTests = false; + Assume.group(TestGroup.JMXMP); + runTests = true; super.onSetUp(); this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer()); try { @@ -73,8 +71,12 @@ public class RemoteMBeanClientInterceptorTestsIgnore extends MBeanClientIntercep 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/export/CustomEditorConfigurerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java index 2c71236d78a..19019011142 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 59740fa0db4..f2bee326688 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 26b0af991d0..c08a9f73b2f 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. @@ -33,8 +33,8 @@ 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.TestBean; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; @@ -48,8 +48,10 @@ 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 org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.TestBean; -import test.interceptor.NopInterceptor; +import static org.junit.Assert.*; /** * Integration tests for the {@link MBeanExporter} class. @@ -67,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... @@ -81,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... @@ -95,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() { @@ -118,6 +123,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testWithSuppliedMBeanServer() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); @@ -128,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()); @@ -137,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()); @@ -154,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())); @@ -171,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())); @@ -190,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())); @@ -211,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())); @@ -221,6 +233,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testWithMBeanExporterListeners() throws Exception { MockMBeanExporterListener listener1 = new MockMBeanExporterListener(); MockMBeanExporterListener listener2 = new MockMBeanExporterListener(); @@ -236,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"); @@ -261,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(); @@ -279,6 +294,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertNotNull(instance); } + @Test public void testRegisterIgnoreExisting() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); @@ -312,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); @@ -340,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"; @@ -369,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(); @@ -387,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(); @@ -406,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(); @@ -429,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(); @@ -451,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(); @@ -469,6 +492,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { ObjectNameManager.getInstance(OBJECT_NAME)); } + @Test public void testSetAutodetectModeToOutOfRangeNegativeValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -479,6 +503,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeToOutOfRangePositiveValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -489,6 +514,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToNull() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -499,6 +525,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToAnEmptyString() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -509,6 +536,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToAWhitespacedString() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -519,6 +547,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToARubbishValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -529,6 +558,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testNotRunningInBeanFactoryAndPassedBeanNameToExport() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -542,6 +572,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testNotRunningInBeanFactoryAndAutodetectionIsOn() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -556,6 +587,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { /** * SPR-2158 */ + @Test public void testMBeanIsNotUnregisteredSpuriouslyIfSomeExternalProcessHasUnregisteredMBean() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); @@ -575,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); @@ -596,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); @@ -620,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 45244123079..a6423dcee8d 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 a6abda7ed2e..2237fcc1553 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 c95000c59da..256372eb1bf 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 d74787b7f81..11c68dcb99f 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 59b71a58b27..42962c5f642 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 @@ -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,31 +47,38 @@ 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); MBeanInfo inf = getMBeanInfo(); assertEquals("Incorrect number of operations registered", getExpectedOperationCount(), inf.getOperations().length); } + @Test public void testRegisterAttributes() throws Exception { IJmxTestBean bean = getBean(); + assertNotNull(bean); MBeanInfo inf = getMBeanInfo(); assertEquals("Incorrect number of attributes registered", 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(); @@ -82,6 +93,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { } } + @Test public void testGetMBeanOperationInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo[] inf = info.getOperations(); @@ -96,6 +108,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { } } + @Test public void testDescriptionNotNull() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); @@ -103,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")); @@ -110,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"); @@ -117,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", @@ -124,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(); @@ -139,6 +156,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { desc.getFieldValue("setMethod")); } + @Test public void testAttributeHasCorrespondingOperations() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); @@ -157,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 4c7c414d850..0c3ece78395 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 @@ -26,14 +26,16 @@ 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; import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.support.ObjectNameManager; +import org.springframework.tests.aop.interceptor.NopInterceptor; -import test.interceptor.NopInterceptor; +import static org.junit.Assert.*; /** * @author Rob Harrop @@ -45,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); @@ -58,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); @@ -68,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); @@ -84,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"); @@ -93,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(); @@ -112,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(); @@ -122,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(); @@ -130,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"); @@ -143,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(); @@ -170,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); @@ -180,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(); @@ -192,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 d4034ed4494..e7bb1d68c9e 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 dc9db0fc5e2..1a485f377e6 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. @@ -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,9 +43,10 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse assertFalse("Age is not writable", attr.isWritable()); } + @Test 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) { @@ -47,9 +54,10 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse } } + @Test public void testWithNonInterface() throws Exception { try { - InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("JmxTestBean"); + getWithMapping("JmxTestBean"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { @@ -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 2c2a8618eb1..ea234b09e8c 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 35fe1082703..aa1e2d57c22 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 f037d87bcb7..6b12c74d971 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 8a492930066..53335e50d70 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 062a45febd7..10b1985515b 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 2b0bbaeefcf..d85f42b508e 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,18 @@ package org.springframework.jmx.export.assembler; +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 { @@ -48,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); @@ -56,6 +64,14 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler assertFalse(attr.isWritable()); } + @Test + 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"; 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 b108c30e01d..79790d3963b 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/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 ef244b085e5..6d66caa79cf 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,23 +28,36 @@ import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; +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 + * @author Chris Beams */ -// 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"; + 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 { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); @@ -56,6 +69,7 @@ public class ConnectorServerFactoryBeanTestsIgnore extends AbstractMBeanServerTe } } + @Test public void testStartupWithSuppliedServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors @@ -72,6 +86,7 @@ public class ConnectorServerFactoryBeanTestsIgnore extends AbstractMBeanServerTe } } + @Test public void testRegisterWithMBeanServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors @@ -89,6 +104,7 @@ public class ConnectorServerFactoryBeanTestsIgnore extends AbstractMBeanServerTe } } + @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 598bc73e8c9..c9c83cffaee 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,9 +23,13 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; +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 @@ -43,16 +47,9 @@ 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 { + @Test + public void testTestValidConnection() throws Exception { + Assume.group(TestGroup.JMXMP); JMXConnectorServer connectorServer = getConnectorServer(); connectorServer.start(); @@ -75,6 +72,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } + @Test public void testWithNoServiceUrl() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); try { @@ -85,16 +83,9 @@ 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 { + @Test + public void testTestWithLazyConnection() throws Exception { + Assume.group(TestGroup.JMXMP); MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(SERVICE_URL); bean.setConnectOnStartup(false); @@ -116,6 +107,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } + @Test public void testWithLazyConnectionAndNoAccess() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(SERVICE_URL); 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 a99ef772f01..4ad2255d2c4 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 5148742ca42..ad6ac8871ab 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 23bac25d536..917e8dc918f 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 2783f244b18..00000000000 --- 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 71736866063..00000000000 --- 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 883db7bfd3f..00000000000 --- 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 9c268b0f676..00000000000 --- 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/annotation/AsyncExecutionTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java index f679713eb96..028f60c559d 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 { 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 3b3329e0d95..bc30910d5f6 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-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java index e100da3d47d..91bf0f697e6 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 {} 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 4f5b69735ec..095f930c610 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-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java index 7320cea1d19..ddaa2b0fcea 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 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 00000000000..491706f9e31 --- /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 49574ae29d5..90acc959b3b 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. @@ -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); @@ -487,7 +488,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); 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 e0945fab1de..283ee0acf3b 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. @@ -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; @@ -23,7 +26,7 @@ import java.util.TimerTask; import junit.framework.TestCase; -import org.springframework.scheduling.TestMethodInvokingTask; +import org.springframework.tests.context.TestMethodInvokingTask; /** * @author Juergen Hoeller @@ -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-context/src/test/java/org/springframework/scripting/ContextScriptBean.java b/spring-context/src/test/java/org/springframework/scripting/ContextScriptBean.java index 052209d92f8..8c9a0ae2b87 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 ddc139475cc..7ea2ee25901 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 8add303ba8d..05601840108 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 62bfe8b7bf3..72a1e6a39c4 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 5908749d75c..116a7d6ab44 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 c98d2be9fb0..cca1625d3df 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.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); 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 d1b82bfece9..0b0116d2e10 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 58ce5e022aa..eaad85d1f8c 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 a8afa2447f8..1516ac2dbc4 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 3744ad4ea62..2cd55ee7df6 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 a3791761801..0e29267700c 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 102df4b7d65..55f3016d81b 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 org.junit.Before; 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.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 13f5d3c9aa0..5df3894c087 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 71b565f900c..9b63bfc3332 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 a95a2408b54..118feabbc33 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 71736866063..a4e8932e26d 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 4e1641b2cd8..bdad96e32d0 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 883db7bfd3f..3d1452ac29f 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 52b78737175..8847baab541 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-webmvc/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-webmvc/src/test/java/org/springframework/beans/BeanWithObjectProperty.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/BeanWithObjectProperty.java index bb5e71f5cd0..4448962d49c 100644 --- a/spring-webmvc/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 537a5a88335..7bed71f394b 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 8e0f55ce777..a98548867aa 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 94% 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 61f911902c7..a250f329cbd 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 0831e05c584..a5b1eef734e 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 09a8c6aaa8d..7b159f3b3a0 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 b20121d864c..00000000000 --- 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 e64219c59ca..bf2031ba53a 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 9107bb3a59d..77fc0dee24d 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]")); } @@ -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-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java index d5e094a2e1f..947677717ce 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 1c7fe2c708e..83a36cf9558 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 b98fb420072..6d831328c18 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/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java index 5c2dad22a4b..be4f45213a0 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,9 +38,11 @@ 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; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; /** @@ -100,6 +103,20 @@ public class ValidatorFactoryTests { assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); } + @Test + 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 mismatch", errors.getFieldError("address").getRejectedValue(), + instanceOf(ValidAddress.class)); + } + @Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); @@ -193,6 +210,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 +271,6 @@ public class ValidatorFactoryTests { } } - public static class ValidAddress { @NotNull @@ -257,7 +285,6 @@ public class ValidatorFactoryTests { } } - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NameAddressValidator.class) @@ -270,7 +297,6 @@ public class ValidatorFactoryTests { Class[] payload() default {}; } - public static class NameAddressValidator implements ConstraintValidator { @Override @@ -278,8 +304,62 @@ 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; + } + } + + + 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; } } 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 5aa37b61e14..00000000000 --- 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 e0e45d6f142..00000000000 --- 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 193531bcbd0..00000000000 --- 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 32de2322644..00000000000 --- 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/ITestBean.java b/spring-context/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 242d5e38503..00000000000 --- 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 8cef5b23217..00000000000 --- 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 0546fdadebb..00000000000 --- 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 4b98eab870e..00000000000 --- 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 1067cbc26cb..3982b48c7cf 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/cache/config/cache-advice.xml b/spring-context/src/test/resources/org/springframework/cache/config/cache-advice.xml index d9eef4816bb..5ebf54ddcb4 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/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml b/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml index 2b71bd30014..efb31d0297b 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 @@ - + - - 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 dd3fc33004b..00000000000 --- 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 b44c0a9c1b8..00000000000 --- 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-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java b/spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java index 91b15c319df..de0132dae16 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 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 392d02b1fa7..954dd4982ee 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-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 be338f0fc0d..c5ac3bb32d6 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 @@ ]]> - + - + - + 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-jms/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-jms/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770ee..00000000000 --- a/spring-jms/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-jms/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-jms/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439b..00000000000 --- a/spring-jms/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-jms/src/test/java/org/springframework/beans/TestBean.java b/spring-jms/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index fd998fd69bf..00000000000 --- a/spring-jms/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 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-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java index ee45f0f90f4..a8c89b525e8 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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.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/config/jmsNamespaceHandlerTests.xml b/spring-jms/src/test/java/org/springframework/jms/config/jmsNamespaceHandlerTests.xml index b316675c33f..c9431ca417c 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/jmsNamespaceHandlerTests.xml +++ b/spring-jms/src/test/java/org/springframework/jms/config/jmsNamespaceHandlerTests.xml @@ -54,13 +54,13 @@ - + - + - + 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 78c0de6e9fd..cd53ab37a31 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 19912ccc395..a1a40d51e44 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 abcb7a7e663..cbf03b7abaf 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. @@ -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,111 +146,70 @@ 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 { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); - 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 public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); - 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 500874d8a12..1ac040f3f86 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. @@ -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,165 +141,106 @@ 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 public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); - 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 public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); - 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 public Object doInJms(Session session) throws JMSException { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); - 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() { @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; } }); - 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(); Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE); - boolean b = tas.getTransacted(); + tas.getTransacted(); tas.close(); tac.close(); @@ -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 30b71cf1823..15eefc873f7 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 6bd5c571236..8dad2a08e03 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 a41851b5ecf..0781e2916d9 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 8fdf9391088..c673f51a447 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 598c5ada293..ea98f902067 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. @@ -16,11 +16,13 @@ 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; @@ -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()); @@ -89,6 +87,7 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { } + @SuppressWarnings("unused") private static class StubActiveMQActivationSpec extends StubJmsActivationSpec { private int maxSessions; @@ -133,6 +132,7 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { } + @SuppressWarnings("unused") private static class StubWebSphereActivationSpecImpl extends StubJmsActivationSpec { private Destination destination; 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 60ee013dc07..9cdbf341368 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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.beans.ITestBean; -import org.springframework.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 7d4663a2859..8ca5ad2e1f1 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 147987430b3..b903ff36868 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 025ba22fc79..d2054d5bf2c 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 54ca352ea0d..0bce702aaad 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 861179583d7..2f6a06199de 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 e968d8cf28b..504e247ee92 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 133602bcbd8..2afd8e6f9c9 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 9cdf36ef45d..548e0334d19 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 + } } diff --git a/spring-jms/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java b/spring-jms/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java deleted file mode 100644 index b1862dd8937..00000000000 --- a/spring-jms/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-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 ddde103c1d4..5871bb8a87e 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. @@ -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. @@ -150,8 +162,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 +200,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 @@ -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"); } @@ -358,7 +444,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 +672,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 dea7f1a1393..f2814150087 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-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java index e125abf2b71..b0aac2d2bbe 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-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 809ced77e67..6715263e756 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; diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletInputStream.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletInputStream.java deleted file mode 100644 index 1b8cf3eeba6..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletInputStream.java +++ /dev/null @@ -1,68 +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.InputStream; -import javax.servlet.ServletInputStream; - -import org.springframework.util.Assert; - -/** - * Delegating implementation of {@link javax.servlet.ServletInputStream}. - * - *

    Used by {@link MockHttpServletRequest}; typically not directly - * used for testing application controllers. - * - * @author Juergen Hoeller - * @since 1.0.2 - * @see MockHttpServletRequest - */ -public class DelegatingServletInputStream extends ServletInputStream { - - private final InputStream sourceStream; - - - /** - * Create a DelegatingServletInputStream for the given source stream. - * @param sourceStream the source stream (never {@code null}) - */ - public DelegatingServletInputStream(InputStream sourceStream) { - Assert.notNull(sourceStream, "Source InputStream must not be null"); - this.sourceStream = sourceStream; - } - - /** - * Return the underlying source stream (never {@code null}). - */ - public final InputStream getSourceStream() { - return this.sourceStream; - } - - - @Override - public int read() throws IOException { - return this.sourceStream.read(); - } - - @Override - public void close() throws IOException { - super.close(); - this.sourceStream.close(); - } - -} diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java deleted file mode 100644 index d580974a608..00000000000 --- a/spring-orm-hibernate4/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-orm-hibernate4/src/test/java/org/springframework/mock/web/HeaderValueHolder.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/HeaderValueHolder.java deleted file mode 100644 index e8f5e91dfb6..00000000000 --- a/spring-orm-hibernate4/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-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterChain.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterChain.java deleted file mode 100644 index bb1fa0ee839..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterChain.java +++ /dev/null @@ -1,184 +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.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; - -/** - *

    Mock implementation of the {@link javax.servlet.FilterChain} interface. Used - * for testing the web framework; also useful for testing custom - * {@link javax.servlet.Filter} implementations. - * - *

    A {@link org.springframework.mock.web.MockFilterChain} can be configured with one or more filters and a - * Servlet to invoke. The first time the chain is called, it invokes all filters - * and the Servlet, and saves the request and response. Subsequent invocations - * raise an {@link IllegalStateException} unless {@link #reset()} is called. - * - * @author Juergen Hoeller - * @author Rob Winch - * @author Rossen Stoyanchev - * - * @since 2.0.3 - * @see org.springframework.mock.web.MockFilterConfig - * @see org.springframework.mock.web.PassThroughFilterChain - */ -public class MockFilterChain implements FilterChain { - - private ServletRequest request; - - private ServletResponse response; - - private final List filters; - - private Iterator iterator; - - - /** - * Register a single do-nothing {@link javax.servlet.Filter} implementation. The first - * invocation saves the request and response. Subsequent invocations raise - * an {@link IllegalStateException} unless {@link #reset()} is called. - */ - public MockFilterChain() { - this.filters = Collections.emptyList(); - } - - /** - * Create a FilterChain with a Servlet. - * - * @param servlet the Servlet to invoke - * @since 3.2 - */ - public MockFilterChain(Servlet servlet) { - this.filters = initFilterList(servlet); - } - - /** - * Create a {@code FilterChain} with Filter's and a Servlet. - * - * @param servlet the {@link javax.servlet.Servlet} to invoke in this {@link javax.servlet.FilterChain} - * @param filters the {@link javax.servlet.Filter}'s to invoke in this {@link javax.servlet.FilterChain} - * @since 3.2 - */ - public MockFilterChain(Servlet servlet, Filter... filters) { - Assert.notNull(filters, "filters cannot be null"); - Assert.noNullElements(filters, "filters cannot contain null values"); - this.filters = initFilterList(servlet, filters); - } - - private static List initFilterList(Servlet servlet, Filter... filters) { - Filter[] allFilters = ObjectUtils.addObjectToArray(filters, new ServletFilterProxy(servlet)); - return Arrays.asList(allFilters); - } - - /** - * Return the request that {@link #doFilter} has been called with. - */ - public ServletRequest getRequest() { - return this.request; - } - - /** - * Return the response that {@link #doFilter} has been called with. - */ - public ServletResponse getResponse() { - return this.response; - } - - /** - * Invoke registered {@link javax.servlet.Filter}s and/or {@link javax.servlet.Servlet} also saving the - * request and response. - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - - if (this.request != null) { - throw new IllegalStateException("This FilterChain has already been called!"); - } - - if (this.iterator == null) { - this.iterator = this.filters.iterator(); - } - - if (this.iterator.hasNext()) { - Filter nextFilter = this.iterator.next(); - nextFilter.doFilter(request, response, this); - } - - this.request = request; - this.response = response; - } - - /** - * Reset the {@link org.springframework.mock.web.MockFilterChain} allowing it to be invoked again. - */ - public void reset() { - this.request = null; - this.response = null; - this.iterator = null; - } - - - /** - * A filter that simply delegates to a Servlet. - */ - private static class ServletFilterProxy implements Filter { - - private final Servlet delegateServlet; - - private ServletFilterProxy(Servlet servlet) { - Assert.notNull(servlet, "servlet cannot be null"); - this.delegateServlet = servlet; - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - - this.delegateServlet.service(request, response); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - @Override - public void destroy() { - } - - @Override - public String toString() { - return this.delegateServlet.toString(); - } - } - -} diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterConfig.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterConfig.java deleted file mode 100644 index 99e7722f335..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterConfig.java +++ /dev/null @@ -1,108 +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.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.servlet.FilterConfig} interface. - * - *

    Used for testing the web framework; also useful for testing - * custom {@link javax.servlet.Filter} implementations. - * - * @author Juergen Hoeller - * @since 1.0.2 - * @see MockFilterChain - * @see PassThroughFilterChain - */ -public class MockFilterConfig implements FilterConfig { - - private final ServletContext servletContext; - - private final String filterName; - - private final Map initParameters = new LinkedHashMap(); - - - /** - * Create a new MockFilterConfig with a default {@link MockServletContext}. - */ - public MockFilterConfig() { - this(null, ""); - } - - /** - * Create a new MockFilterConfig with a default {@link MockServletContext}. - * @param filterName the name of the filter - */ - public MockFilterConfig(String filterName) { - this(null, filterName); - } - - /** - * Create a new MockFilterConfig. - * @param servletContext the ServletContext that the servlet runs in - */ - public MockFilterConfig(ServletContext servletContext) { - this(servletContext, ""); - } - - /** - * Create a new MockFilterConfig. - * @param servletContext the ServletContext that the servlet runs in - * @param filterName the name of the filter - */ - public MockFilterConfig(ServletContext servletContext, String filterName) { - this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); - this.filterName = filterName; - } - - - @Override - public String getFilterName() { - return filterName; - } - - @Override - public ServletContext getServletContext() { - return servletContext; - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - -} diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java deleted file mode 100644 index 8d0b813d481..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java +++ /dev/null @@ -1,964 +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.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.security.Principal; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.springframework.util.Assert; -import org.springframework.util.LinkedCaseInsensitiveMap; - -/** - * Mock implementation of the {@link javax.servlet.http.HttpServletRequest} interface. - * - *

    Compatible with Servlet 2.5 and partially with Servlet 3.0 (notable exceptions: - * the {@code getPart(s)} and {@code startAsync} families of methods). - * - * @author Juergen Hoeller - * @author Rod Johnson - * @author Rick Evans - * @author Mark Fisher - * @author Sam Brannen - * @since 1.0.2 - */ -public class MockHttpServletRequest implements HttpServletRequest { - - /** - * The default protocol: 'http'. - */ - public static final String DEFAULT_PROTOCOL = "http"; - - /** - * The default server address: '127.0.0.1'. - */ - public static final String DEFAULT_SERVER_ADDR = "127.0.0.1"; - - /** - * The default server name: 'localhost'. - */ - public static final String DEFAULT_SERVER_NAME = "localhost"; - - /** - * The default server port: '80'. - */ - public static final int DEFAULT_SERVER_PORT = 80; - - /** - * The default remote address: '127.0.0.1'. - */ - public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1"; - - /** - * The default remote host: 'localhost'. - */ - public static final String DEFAULT_REMOTE_HOST = "localhost"; - - private static final String CONTENT_TYPE_HEADER = "Content-Type"; - - private static final String CHARSET_PREFIX = "charset="; - - private boolean active = true; - - // --------------------------------------------------------------------- - // ServletRequest properties - // --------------------------------------------------------------------- - - private final Map attributes = new LinkedHashMap(); - - private String characterEncoding; - - private byte[] content; - - private String contentType; - - private final Map parameters = new LinkedHashMap(16); - - private String protocol = DEFAULT_PROTOCOL; - - private String scheme = DEFAULT_PROTOCOL; - - private String serverName = DEFAULT_SERVER_NAME; - - private int serverPort = DEFAULT_SERVER_PORT; - - private String remoteAddr = DEFAULT_REMOTE_ADDR; - - private String remoteHost = DEFAULT_REMOTE_HOST; - - /** List of locales in descending order */ - private final List locales = new LinkedList(); - - private boolean secure = false; - - private final ServletContext servletContext; - - private int remotePort = DEFAULT_SERVER_PORT; - - private String localName = DEFAULT_SERVER_NAME; - - private String localAddr = DEFAULT_SERVER_ADDR; - - private int localPort = DEFAULT_SERVER_PORT; - - // --------------------------------------------------------------------- - // HttpServletRequest properties - // --------------------------------------------------------------------- - - private String authType; - - private Cookie[] cookies; - - private final Map headers = new LinkedCaseInsensitiveMap(); - - private String method; - - private String pathInfo; - - private String contextPath = ""; - - private String queryString; - - private String remoteUser; - - private final Set userRoles = new HashSet(); - - private Principal userPrincipal; - - private String requestedSessionId; - - private String requestURI; - - private String servletPath = ""; - - private HttpSession session; - - private boolean requestedSessionIdValid = true; - - private boolean requestedSessionIdFromCookie = true; - - private boolean requestedSessionIdFromURL = false; - - - // --------------------------------------------------------------------- - // Constructors - // --------------------------------------------------------------------- - - /** - * Create a new {@code MockHttpServletRequest} with a default - * {@link org.springframework.mock.web.MockServletContext}. - * @see #MockHttpServletRequest(javax.servlet.ServletContext, String, String) - */ - public MockHttpServletRequest() { - this(null, "", ""); - } - - /** - * Create a new {@code MockHttpServletRequest} with a default - * {@link MockServletContext}. - * @param method the request method (may be {@code null}) - * @param requestURI the request URI (may be {@code null}) - * @see #setMethod - * @see #setRequestURI - * @see #MockHttpServletRequest(javax.servlet.ServletContext, String, String) - */ - public MockHttpServletRequest(String method, String requestURI) { - this(null, method, requestURI); - } - - /** - * Create a new {@code MockHttpServletRequest} with the supplied {@link javax.servlet.ServletContext}. - * @param servletContext the ServletContext that the request runs in (may be - * {@code null} to use a default {@link MockServletContext}) - * @see #MockHttpServletRequest(javax.servlet.ServletContext, String, String) - */ - public MockHttpServletRequest(ServletContext servletContext) { - this(servletContext, "", ""); - } - - /** - * Create a new {@code MockHttpServletRequest} with the supplied {@link javax.servlet.ServletContext}, - * {@code method}, and {@code requestURI}. - *

    The preferred locale will be set to {@link java.util.Locale#ENGLISH}. - * @param servletContext the ServletContext that the request runs in (may be - * {@code null} to use a default {@link MockServletContext}) - * @param method the request method (may be {@code null}) - * @param requestURI the request URI (may be {@code null}) - * @see #setMethod - * @see #setRequestURI - * @see #setPreferredLocales - * @see MockServletContext - */ - public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) { - this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); - this.method = method; - this.requestURI = requestURI; - this.locales.add(Locale.ENGLISH); - } - - // --------------------------------------------------------------------- - // Lifecycle methods - // --------------------------------------------------------------------- - - /** - * Return the ServletContext that this request is associated with. (Not - * available in the standard HttpServletRequest interface for some reason.) - */ - public ServletContext getServletContext() { - return this.servletContext; - } - - /** - * Return whether this request is still active (that is, not completed yet). - */ - public boolean isActive() { - return this.active; - } - - /** - * Mark this request as completed, keeping its state. - */ - public void close() { - this.active = false; - } - - /** - * Invalidate this request, clearing its state. - */ - public void invalidate() { - close(); - clearAttributes(); - } - - /** - * Check whether this request is still active (that is, not completed yet), - * throwing an IllegalStateException if not active anymore. - */ - protected void checkActive() throws IllegalStateException { - if (!this.active) { - throw new IllegalStateException("Request is not active anymore"); - } - } - - // --------------------------------------------------------------------- - // ServletRequest interface - // --------------------------------------------------------------------- - - @Override - public Object getAttribute(String name) { - checkActive(); - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - checkActive(); - return Collections.enumeration(this.attributes.keySet()); - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - @Override - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - updateContentTypeHeader(); - } - - private void updateContentTypeHeader() { - if (this.contentType != null) { - StringBuilder sb = new StringBuilder(this.contentType); - if (!this.contentType.toLowerCase().contains(CHARSET_PREFIX) && this.characterEncoding != null) { - sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding); - } - doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true); - } - } - - public void setContent(byte[] content) { - this.content = content; - } - - @Override - public int getContentLength() { - return (this.content != null ? this.content.length : -1); - } - - 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; - } - updateContentTypeHeader(); - } - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public ServletInputStream getInputStream() { - if (this.content != null) { - return new DelegatingServletInputStream(new ByteArrayInputStream(this.content)); - } - else { - return null; - } - } - - /** - * Set a single value for the specified HTTP parameter. - *

    If there are already one or more values registered for the given - * parameter name, they will be replaced. - */ - public void setParameter(String name, String value) { - setParameter(name, new String[] { value }); - } - - /** - * Set an array of values for the specified HTTP parameter. - *

    If there are already one or more values registered for the given - * parameter name, they will be replaced. - */ - public void setParameter(String name, String[] values) { - Assert.notNull(name, "Parameter name must not be null"); - this.parameters.put(name, values); - } - - /** - * Sets all provided parameters replacing any existing - * values for the provided parameter names. To add without replacing - * existing values, use {@link #addParameters(java.util.Map)}. - */ - @SuppressWarnings("rawtypes") - 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() + "]"); - Object value = params.get(key); - if (value instanceof String) { - this.setParameter((String) key, (String) value); - } - else if (value instanceof String[]) { - this.setParameter((String) key, (String[]) value); - } - else { - throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" - + String.class.getName() + "]"); - } - } - } - - /** - * Add a single value for the specified HTTP parameter. - *

    If there are already one or more values registered for the given - * 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 }); - } - - /** - * Add an array of values for the specified HTTP parameter. - *

    If there are already one or more values registered for the given - * parameter name, the given values will be added to the end of the list. - */ - public void addParameter(String name, String[] values) { - Assert.notNull(name, "Parameter name must not be null"); - String[] oldArr = this.parameters.get(name); - if (oldArr != null) { - String[] newArr = new String[oldArr.length + values.length]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - System.arraycopy(values, 0, newArr, oldArr.length, values.length); - this.parameters.put(name, newArr); - } - else { - this.parameters.put(name, values); - } - } - - /** - * Adds all provided parameters without replacing any - * existing values. To replace existing values, use - * {@link #setParameters(java.util.Map)}. - */ - @SuppressWarnings("rawtypes") - 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() + "]"); - Object value = params.get(key); - if (value instanceof String) { - this.addParameter((String) key, (String) value); - } - else if (value instanceof String[]) { - this.addParameter((String) key, (String[]) value); - } - else { - throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" - + String.class.getName() + "]"); - } - } - } - - /** - * Remove already registered values for the specified HTTP parameter, if - * any. - */ - public void removeParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - this.parameters.remove(name); - } - - /** - * Removes all existing parameters. - */ - public void removeAllParameters() { - this.parameters.clear(); - } - - @Override - public String getParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - @Override - public Enumeration getParameterNames() { - return Collections.enumeration(this.parameters.keySet()); - } - - @Override - public String[] getParameterValues(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.parameters.get(name); - } - - @Override - public Map getParameterMap() { - return Collections.unmodifiableMap(this.parameters); - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - @Override - public String getProtocol() { - return this.protocol; - } - - public void setScheme(String scheme) { - this.scheme = scheme; - } - - @Override - public String getScheme() { - return this.scheme; - } - - public void setServerName(String serverName) { - this.serverName = serverName; - } - - @Override - public String getServerName() { - return this.serverName; - } - - public void setServerPort(int serverPort) { - this.serverPort = serverPort; - } - - @Override - public int getServerPort() { - return this.serverPort; - } - - @Override - public BufferedReader getReader() throws UnsupportedEncodingException { - if (this.content != null) { - InputStream sourceStream = new ByteArrayInputStream(this.content); - Reader sourceReader = (this.characterEncoding != null) ? new InputStreamReader(sourceStream, - this.characterEncoding) : new InputStreamReader(sourceStream); - return new BufferedReader(sourceReader); - } - else { - return null; - } - } - - public void setRemoteAddr(String remoteAddr) { - this.remoteAddr = remoteAddr; - } - - @Override - public String getRemoteAddr() { - return this.remoteAddr; - } - - public void setRemoteHost(String remoteHost) { - this.remoteHost = remoteHost; - } - - @Override - public String getRemoteHost() { - return this.remoteHost; - } - - @Override - public void setAttribute(String name, Object value) { - checkActive(); - 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) { - checkActive(); - Assert.notNull(name, "Attribute name must not be null"); - this.attributes.remove(name); - } - - /** - * Clear all of this request's attributes. - */ - public void clearAttributes() { - this.attributes.clear(); - } - - /** - * Add a new preferred locale, before any existing locales. - * @see #setPreferredLocales - */ - public void addPreferredLocale(Locale locale) { - Assert.notNull(locale, "Locale must not be null"); - this.locales.add(0, locale); - } - - /** - * Set the list of preferred locales, in descending order, effectively replacing - * any existing locales. - * @see #addPreferredLocale - * @since 3.2 - */ - public void setPreferredLocales(List locales) { - Assert.notEmpty(locales, "preferred locales list must not be empty"); - this.locales.clear(); - this.locales.addAll(locales); - } - - @Override - public Locale getLocale() { - return this.locales.get(0); - } - - @Override - public Enumeration getLocales() { - return Collections.enumeration(this.locales); - } - - public void setSecure(boolean secure) { - this.secure = secure; - } - - @Override - public boolean isSecure() { - return this.secure; - } - - @Override - public RequestDispatcher getRequestDispatcher(String path) { - return new MockRequestDispatcher(path); - } - - @Override - public String getRealPath(String path) { - return this.servletContext.getRealPath(path); - } - - public void setRemotePort(int remotePort) { - this.remotePort = remotePort; - } - - @Override - public int getRemotePort() { - return this.remotePort; - } - - public void setLocalName(String localName) { - this.localName = localName; - } - - @Override - public String getLocalName() { - return this.localName; - } - - public void setLocalAddr(String localAddr) { - this.localAddr = localAddr; - } - - @Override - public String getLocalAddr() { - return this.localAddr; - } - - public void setLocalPort(int localPort) { - this.localPort = localPort; - } - - @Override - public int getLocalPort() { - return this.localPort; - } - - // --------------------------------------------------------------------- - // HttpServletRequest interface - // --------------------------------------------------------------------- - - public void setAuthType(String authType) { - this.authType = authType; - } - - @Override - public String getAuthType() { - return this.authType; - } - - public void setCookies(Cookie... cookies) { - this.cookies = cookies; - } - - @Override - public Cookie[] getCookies() { - return this.cookies; - } - - /** - * Add a header entry for the given name. - *

    If there was no entry for that header name before, the value will be used - * as-is. In case of an existing entry, a String array will be created, - * adding the given value (more specifically, its toString representation) - * as further element. - *

    Multiple values can only be stored as list of Strings, following the - * Servlet spec (see {@code getHeaders} accessor). As alternative to - * repeated {@code addHeader} calls for individual elements, you can - * use a single call with an entire array or Collection of values as - * parameter. - * @see #getHeaderNames - * @see #getHeader - * @see #getHeaders - * @see #getDateHeader - * @see #getIntHeader - */ - public void addHeader(String name, Object value) { - if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) { - setContentType((String) value); - return; - } - doAddHeaderValue(name, value, false); - } - - @SuppressWarnings("rawtypes") - 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 || replace) { - header = new HeaderValueHolder(); - this.headers.put(name, header); - } - if (value instanceof Collection) { - header.addValues((Collection) value); - } - else if (value.getClass().isArray()) { - header.addValueArray(value); - } - else { - header.addValue(value); - } - } - - @Override - public long getDateHeader(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - Object value = (header != null ? header.getValue() : null); - if (value instanceof Date) { - return ((Date) value).getTime(); - } - else if (value instanceof Number) { - return ((Number) value).longValue(); - } - else if (value != null) { - throw new IllegalArgumentException("Value for header '" + name + "' is neither a Date nor a Number: " - + value); - } - else { - return -1L; - } - } - - @Override - public String getHeader(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return (header != null ? header.getStringValue() : null); - } - - @Override - public Enumeration getHeaders(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return Collections.enumeration(header != null ? header.getStringValues() : new LinkedList()); - } - - @Override - public Enumeration getHeaderNames() { - return Collections.enumeration(this.headers.keySet()); - } - - @Override - public int getIntHeader(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - Object value = (header != null ? header.getValue() : null); - if (value instanceof Number) { - return ((Number) value).intValue(); - } - else if (value instanceof String) { - return Integer.parseInt((String) value); - } - else if (value != null) { - throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value); - } - else { - return -1; - } - } - - public void setMethod(String method) { - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - - public void setPathInfo(String pathInfo) { - this.pathInfo = pathInfo; - } - - @Override - public String getPathInfo() { - return this.pathInfo; - } - - @Override - public String getPathTranslated() { - return (this.pathInfo != null ? getRealPath(this.pathInfo) : null); - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - - @Override - public String getContextPath() { - return this.contextPath; - } - - public void setQueryString(String queryString) { - this.queryString = queryString; - } - - @Override - public String getQueryString() { - return this.queryString; - } - - public void setRemoteUser(String remoteUser) { - this.remoteUser = remoteUser; - } - - @Override - public String getRemoteUser() { - return this.remoteUser; - } - - public void addUserRole(String role) { - this.userRoles.add(role); - } - - @Override - public boolean isUserInRole(String role) { - return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && ((MockServletContext) this.servletContext).getDeclaredRoles().contains( - role))); - } - - public void setUserPrincipal(Principal userPrincipal) { - this.userPrincipal = userPrincipal; - } - - @Override - public Principal getUserPrincipal() { - return this.userPrincipal; - } - - public void setRequestedSessionId(String requestedSessionId) { - this.requestedSessionId = requestedSessionId; - } - - @Override - public String getRequestedSessionId() { - return this.requestedSessionId; - } - - public void setRequestURI(String requestURI) { - this.requestURI = requestURI; - } - - @Override - public String getRequestURI() { - return this.requestURI; - } - - @Override - public StringBuffer getRequestURL() { - StringBuffer url = new StringBuffer(this.scheme); - url.append("://").append(this.serverName).append(':').append(this.serverPort); - url.append(getRequestURI()); - return url; - } - - public void setServletPath(String servletPath) { - this.servletPath = servletPath; - } - - @Override - public String getServletPath() { - return this.servletPath; - } - - public void setSession(HttpSession session) { - this.session = session; - if (session instanceof MockHttpSession) { - MockHttpSession mockSession = ((MockHttpSession) session); - mockSession.access(); - } - } - - @Override - public HttpSession getSession(boolean create) { - checkActive(); - // Reset session if invalidated. - if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) { - this.session = null; - } - // Create new session if necessary. - if (this.session == null && create) { - this.session = new MockHttpSession(this.servletContext); - } - return this.session; - } - - @Override - public HttpSession getSession() { - return getSession(true); - } - - public void setRequestedSessionIdValid(boolean requestedSessionIdValid) { - this.requestedSessionIdValid = requestedSessionIdValid; - } - - @Override - public boolean isRequestedSessionIdValid() { - return this.requestedSessionIdValid; - } - - public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) { - this.requestedSessionIdFromCookie = requestedSessionIdFromCookie; - } - - @Override - public boolean isRequestedSessionIdFromCookie() { - return this.requestedSessionIdFromCookie; - } - - public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) { - this.requestedSessionIdFromURL = requestedSessionIdFromURL; - } - - @Override - public boolean isRequestedSessionIdFromURL() { - return this.requestedSessionIdFromURL; - } - - @Override - public boolean isRequestedSessionIdFromUrl() { - return isRequestedSessionIdFromURL(); - } - - public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { - return (this.userPrincipal != null && this.remoteUser != null && this.authType != null); - } - - public void login(String username, String password) throws ServletException { - throw new ServletException("Username-password authentication not supported - override the login method"); - } - - public void logout() throws ServletException { - this.userPrincipal = null; - this.remoteUser = null; - this.authType = null; - } - -} diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java deleted file mode 100644 index 5a2b7fd1aa8..00000000000 --- a/spring-orm-hibernate4/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-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpSession.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpSession.java deleted file mode 100644 index f7b086c9872..00000000000 --- a/spring-orm-hibernate4/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 org.springframework.mock.web.MockServletContext}. - * - * @see org.springframework.mock.web.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-orm-hibernate4/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java deleted file mode 100644 index 46924b0893e..00000000000 --- a/spring-orm-hibernate4/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 org.springframework.mock.web.MockHttpServletResponse}, unwrapping - * {@link javax.servlet.http.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-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletConfig.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletConfig.java deleted file mode 100644 index be7ebf808e5..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletConfig.java +++ /dev/null @@ -1,107 +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.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.servlet.ServletConfig} interface. - * - *

    Used for testing the web framework; typically not necessary for - * testing application controllers. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 1.0.2 - */ -public class MockServletConfig implements ServletConfig { - - private final ServletContext servletContext; - - private final String servletName; - - private final Map initParameters = new LinkedHashMap(); - - - /** - * Create a new MockServletConfig with a default {@link MockServletContext}. - */ - public MockServletConfig() { - this(null, ""); - } - - /** - * Create a new MockServletConfig with a default {@link MockServletContext}. - * @param servletName the name of the servlet - */ - public MockServletConfig(String servletName) { - this(null, servletName); - } - - /** - * Create a new MockServletConfig. - * @param servletContext the ServletContext that the servlet runs in - */ - public MockServletConfig(ServletContext servletContext) { - this(servletContext, ""); - } - - /** - * Create a new MockServletConfig. - * @param servletContext the ServletContext that the servlet runs in - * @param servletName the name of the servlet - */ - public MockServletConfig(ServletContext servletContext, String servletName) { - this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); - this.servletName = servletName; - } - - - @Override - public String getServletName() { - return this.servletName; - } - - @Override - public ServletContext getServletContext() { - return this.servletContext; - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - -} diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletContext.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletContext.java deleted file mode 100644 index 70ae2b53ce3..00000000000 --- a/spring-orm-hibernate4/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 org.springframework.mock.web.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 javax.servlet.RequestDispatcher} (typically a {@link org.springframework.mock.web.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 javax.servlet.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 javax.servlet.RequestDispatcher} and {@link #registerNamedDispatcher replaces} - * it with a {@link org.springframework.mock.web.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-orm-hibernate4/src/test/java/org/springframework/mock/web/PassThroughFilterChain.java b/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/PassThroughFilterChain.java deleted file mode 100644 index 080b8534eaf..00000000000 --- a/spring-orm-hibernate4/src/test/java/org/springframework/mock/web/PassThroughFilterChain.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.mock.web; - -import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.springframework.util.Assert; - -/** - * Implementation of the {@link javax.servlet.FilterConfig} interface which - * simply passes the call through to a given Filter/FilterChain combination - * (indicating the next Filter in the chain along with the FilterChain that it is - * supposed to work on) or to a given Servlet (indicating the end of the chain). - * - * @author Juergen Hoeller - * @since 2.0.3 - * @see javax.servlet.Filter - * @see javax.servlet.Servlet - * @see MockFilterChain - */ -public class PassThroughFilterChain implements FilterChain { - - private Filter filter; - - private FilterChain nextFilterChain; - - private Servlet servlet; - - - /** - * Create a new PassThroughFilterChain that delegates to the given Filter, - * calling it with the given FilterChain. - * @param filter the Filter to delegate to - * @param nextFilterChain the FilterChain to use for that next Filter - */ - public PassThroughFilterChain(Filter filter, FilterChain nextFilterChain) { - Assert.notNull(filter, "Filter must not be null"); - Assert.notNull(nextFilterChain, "'FilterChain must not be null"); - this.filter = filter; - this.nextFilterChain = nextFilterChain; - } - - /** - * Create a new PassThroughFilterChain that delegates to the given Servlet. - * @param servlet the Servlet to delegate to - */ - public PassThroughFilterChain(Servlet servlet) { - Assert.notNull(servlet, "Servlet must not be null"); - this.servlet = servlet; - } - - - /** - * Pass the call on to the Filter/Servlet. - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException { - if (this.filter != null) { - this.filter.doFilter(request, response, this.nextFilterChain); - } - else { - this.servlet.service(request, response); - } - } - -} 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 26bdd97e292..f235fc196e0 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(); } 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 d3d1e137339..abd06c801ac 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 */ @@ -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/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java index dcf15059d3a..1c7353697ad 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; 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 49c49a69760..a6e13b673da 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 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 d944ef497dc..72f5ee42ea7 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)) { 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 38d0f7263a4..9d058158b91 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/main/java/org/springframework/orm/jdo/JdoTemplate.java b/spring-orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java index ce0f61aefcb..6ed2028384f 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-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java b/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java index 9419950001e..044cb72be38 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-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 ac9c408f02c..39c437e8cdf 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); } } diff --git a/spring-orm/src/test/java/org/springframework/beans/Colour.java b/spring-orm/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc6..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-orm/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3f..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/IOther.java b/spring-orm/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185a..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/ITestBean.java b/spring-orm/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510dd..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-orm/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770ee..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-orm/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439b..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/TestBean.java b/spring-orm/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 6d71de75764..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java b/spring-orm/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java deleted file mode 100644 index 44cc004f89e..00000000000 --- a/spring-orm/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.config; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.ObjectFactory; - -/** - * @author Juergen Hoeller - */ -@SuppressWarnings("serial") -public class SimpleMapScope implements Scope, Serializable { - - private final Map map = new HashMap(); - - private final List callbacks = new LinkedList(); - - - public SimpleMapScope() { - } - - public final Map getMap() { - return this.map; - } - - - @Override - public Object get(String name, ObjectFactory objectFactory) { - synchronized (this.map) { - Object scopedObject = this.map.get(name); - if (scopedObject == null) { - scopedObject = objectFactory.getObject(); - this.map.put(name, scopedObject); - } - return scopedObject; - } - } - - @Override - public Object remove(String name) { - synchronized (this.map) { - return this.map.remove(name); - } - } - - @Override - public void registerDestructionCallback(String name, Runnable callback) { - this.callbacks.add(callback); - } - - @Override - public Object resolveContextualObject(String key) { - return null; - } - - public void close() { - for (Iterator it = this.callbacks.iterator(); it.hasNext();) { - Runnable runnable = (Runnable) it.next(); - runnable.run(); - } - } - - @Override - public String getConversationId() { - return null; - } - -} diff --git a/spring-orm/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java b/spring-orm/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java deleted file mode 100644 index 71736866063..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java b/spring-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java deleted file mode 100644 index 4e1641b2cd8..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java b/spring-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java deleted file mode 100644 index 883db7bfd3f..00000000000 --- a/spring-orm/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-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java index ba1415f6402..498005295ea 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 c44277644b5..6f5ef6d62d2 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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,9 +47,11 @@ 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.transaction.MockJtaTransaction; +import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; @@ -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 680520f6de4..fd1ae832b38 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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.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 707d17b9fe4..d4d12ba036b 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. @@ -25,8 +25,6 @@ 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,6 +37,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; @@ -56,65 +57,43 @@ 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 * @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 +131,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 +180,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 +220,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 +283,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 +342,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 +388,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 +436,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(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(); + @Test + public void testParticipatingTransactionWithRequiresNew() throws Exception { + 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 +496,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(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(); + @Test + public void testParticipatingTransactionWithNotSupported() throws Exception { + 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 +555,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 +604,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 +684,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 +732,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 +784,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 +829,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 +901,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 +960,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 +1054,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 +1132,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 +1152,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 +1213,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 +1263,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 +1314,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 +1358,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 +1385,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(); } } 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 2cec656f949..0b61d591603 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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.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(); @@ -484,10 +497,10 @@ public class LocalSessionFactoryBeanTests extends TestCase { sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); Properties classCache = new Properties(); - classCache.setProperty("org.springframework.beans.TestBean", "read-write"); + classCache.setProperty("org.springframework.tests.sample.beans.TestBean", "read-write"); sfb.setEntityCacheStrategies(classCache); Properties collectionCache = new Properties(); - collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only"); + collectionCache.setProperty("org.springframework.tests.sample.beans.TestBean.friends", "read-only"); sfb.setCollectionCacheStrategies(collectionCache); sfb.afterPropertiesSet(); @@ -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(); @@ -523,10 +537,10 @@ public class LocalSessionFactoryBeanTests extends TestCase { sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); Properties classCache = new Properties(); - classCache.setProperty("org.springframework.beans.TestBean", "read-write,myRegion"); + classCache.setProperty("org.springframework.tests.sample.beans.TestBean", "read-write,myRegion"); sfb.setEntityCacheStrategies(classCache); Properties collectionCache = new Properties(); - collectionCache.setProperty("org.springframework.beans.TestBean.friends", "read-only,myRegion"); + collectionCache.setProperty("org.springframework.tests.sample.beans.TestBean.friends", "read-only,myRegion"); sfb.setCollectionCacheStrategies(collectionCache); sfb.afterPropertiesSet(); @@ -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/filterDefinitions.xml b/spring-orm/src/test/java/org/springframework/orm/hibernate3/filterDefinitions.xml deleted file mode 100644 index 96b19990ac4..00000000000 --- 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/support/HibernateDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java index 2f264aa25f1..8aa465e0e82 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 3bc4f20b2b7..ab82cbcf638 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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.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,54 +36,45 @@ 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; -import org.springframework.transaction.MockJtaTransaction; +import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.support.TransactionSynchronization; 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 41058bb7c4a..a51fc633e9b 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/hibernate3/typeDefinitions.xml b/spring-orm/src/test/java/org/springframework/orm/hibernate3/typeDefinitions.xml deleted file mode 100644 index bd12f319b7f..00000000000 --- 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/ibatis/SqlMapClientTests.java b/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java index 43a44e3498b..91a7277e783 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 d92b60d3f4a..948c4e7ec26 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 21fa381178b..1967c188d53 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,12 +74,10 @@ public class JdoInterceptorTests extends TestCase { finally { TransactionSynchronizationManager.unbindResource(pmf); } - - pmfControl.verify(); - pmControl.verify(); } + @SuppressWarnings("unused") private static class TestInvocation implements MethodInvocation { private PersistenceManagerFactory persistenceManagerFactory; 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 2baf4d205a1..29c882b2b63 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 6dde6a8c5dd..46003776b05 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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.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; @@ -33,17 +34,17 @@ import javax.transaction.Status; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; -import org.springframework.beans.TestBean; 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.transaction.InvalidIsolationLevelException; -import org.springframework.transaction.MockJtaTransaction; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -53,12 +54,17 @@ 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 */ -public class JdoTransactionManagerTests extends TestCase { - - private MockControl pmfControl, pmControl, txControl; +public class JdoTransactionManagerTests { private PersistenceManagerFactory pmf; @@ -67,55 +73,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 +141,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 +181,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 +219,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 +252,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 +273,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 +290,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 +308,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 +327,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 +350,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 +372,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 +393,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 +409,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 +433,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 +461,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 +512,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 +542,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 +576,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,52 +610,30 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Correct result list", result == l); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); + + verify(pm, times(2)).close(); } - 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(); + @Test + 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(); } + @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 +661,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 +705,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 +753,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 +802,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 +823,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 +883,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 +952,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 +979,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 1bf0d91fbb0..4b16a589caf 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 20bc73dbfe2..529bdcabf1b 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 7a5784ac93c..2736e3b6da4 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/jdo/test.properties b/spring-orm/src/test/java/org/springframework/orm/jdo/test.properties deleted file mode 100644 index cd4acea9278..00000000000 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/test.properties +++ /dev/null @@ -1 +0,0 @@ -myKey=myValue 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 80912a34798..cefae3bdf2f 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/ApplicationManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java index 23f241e5ab1..920099caf9c 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-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java index 0f7efcafe7e..9102cd8645a 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 1d4578b372b..0f21f02ea85 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 137912e5b23..43771366636 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 5f2c0d0aa91..959fa0efe9b 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,11 +194,11 @@ public class JpaInterceptorTests extends TestCase { assertEquals(exception, ex); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).close(); } + @SuppressWarnings("unused") private static class TestInvocation implements MethodInvocation { private EntityManagerFactory entityManagerFactory; 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 4d25da36591..64828a43190 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 a1a7db067b6..a343d215372 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 393d316db0a..5f20a375d4b 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 048eb2d4ae9..de6667f543f 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/domain/ContextualPerson.java b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/ContextualPerson.java index 9bc00960fe0..754baa1c87f 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/domain/ContextualPerson.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/ContextualPerson.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. @@ -28,7 +28,7 @@ import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.PersistenceContext; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Configurable; /** diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/domain/Person.java b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/Person.java index 598c07f755c..c1080b493ff 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/domain/Person.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/Person.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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 javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Configurable; /** diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/domain/persistence-multi.xml b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/persistence-multi.xml index 217e8537ff5..d3c57397183 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/domain/persistence-multi.xml +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/domain/persistence-multi.xml @@ -10,7 +10,7 @@ - org.springframework.beans.TestBean + org.springframework.tests.sample.beans.TestBean 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 20d9e5f029b..a35fdac8cad 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-10333.") public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests { @Override diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java index a09e090765a..496d9d641ac 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceXmlParsingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,7 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; import org.springframework.jdbc.datasource.lookup.MapDataSourceLookup; -import org.springframework.mock.jndi.SimpleNamingContextBuilder; +import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; import static org.junit.Assert.*; 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 b2b509f3dfa..4925258a669 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 3431e4a4216..8dd05c32b3d 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 7e84430678c..f7a26112fc5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,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,21 +40,20 @@ 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.config.SimpleMapScope; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.mock.jndi.ExpectedLookupTemplate; import org.springframework.orm.jpa.AbstractEntityManagerFactoryBeanTests; import org.springframework.orm.jpa.DefaultJpaDialect; import org.springframework.orm.jpa.EntityManagerFactoryInfo; import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.stereotype.Repository; +import org.springframework.tests.context.SimpleMapScope; +import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; @@ -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 3296f1f258d..4a783c7d5d5 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(); } } 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 78e8f86af5b..7b743131143 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-10333.") public class TopLinkMultiEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests { diff --git a/spring-orm/src/test/java/org/springframework/transaction/MockJtaTransaction.java b/spring-orm/src/test/java/org/springframework/transaction/MockJtaTransaction.java deleted file mode 100644 index e2066af4d92..00000000000 --- a/spring-orm/src/test/java/org/springframework/transaction/MockJtaTransaction.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.transaction; - -import javax.transaction.Status; -import javax.transaction.Synchronization; -import javax.transaction.xa.XAResource; - -/** - * @author Juergen Hoeller - * @since 31.08.2004 - */ -public class MockJtaTransaction implements javax.transaction.Transaction { - - private Synchronization synchronization; - - @Override - public int getStatus() { - return Status.STATUS_ACTIVE; - } - - @Override - public void registerSynchronization(Synchronization synchronization) { - this.synchronization = synchronization; - } - - public Synchronization getSynchronization() { - return synchronization; - } - - @Override - public boolean enlistResource(XAResource xaResource) { - return false; - } - - @Override - public boolean delistResource(XAResource xaResource, int i) { - return false; - } - - @Override - public void commit() { - } - - @Override - public void rollback() { - } - - @Override - public void setRollbackOnly() { - } - -} diff --git a/spring-orm/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-orm/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index dbe6421093e..00000000000 --- a/spring-orm/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-orm/src/test/resources/org/springframework/beans/factory/xml/child.xml b/spring-orm/src/test/resources/org/springframework/beans/factory/xml/child.xml index 654e76e7fb5..fc90f7905c7 100644 --- a/spring-orm/src/test/resources/org/springframework/beans/factory/xml/child.xml +++ b/spring-orm/src/test/resources/org/springframework/beans/factory/xml/child.xml @@ -8,13 +8,13 @@ - 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 e67e3101362..933e66b7d00 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-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java index fab56e5e5aa..0f23da93c4d 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-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java index 0405e8272e7..131b782c876 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/main/java/org/springframework/oxm/castor/package-info.java b/spring-oxm/src/main/java/org/springframework/oxm/castor/package-info.java index 42f8cdade28..1f1167ab09e 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/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java index 956c0032333..4ffd0c495d6 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); @@ -406,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; } @@ -514,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) { @@ -707,6 +719,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 +731,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); 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 b53c20a5b92..dd36d17b8bf 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 04f53b6973b..00000000000 --- 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); - } - } - -} 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 367b4aa5c15..585640893be 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(); 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 3d7a4978671..43101e62d0a 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-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml b/spring-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml index e85971251c2..f54e293fdf6 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/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 b299f31263d..33fe62fa529 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-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java b/spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java index 054e3b18c9a..87608730ad3 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/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 5b89cef1a7a..1bcb49a5b99 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/MockMvc.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java index a074ff6d147..b18fc3554fa 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()) 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 75a50db9df7..d2e1054a636 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. @@ -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/MockMultipartHttpServletRequestBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java index 8be3cf86ea4..78ff9d2d565 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/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 da96fd9cd22..bb0c109a099 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. @@ -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/result/ContentResultMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java index b39875baaa5..c71dc98b7fd 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/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 61c2f37df67..a2747bb102d 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-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 a97b38aeee2..7e8b7afd635 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. @@ -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 @@ -41,7 +42,7 @@ import org.springframework.web.context.WebApplicationContext; * @author Rob Winch * @since 3.2 */ -public class DefaultMockMvcBuilder extends MockMvcBuilderSupport +public class DefaultMockMvcBuilder extends MockMvcBuilderSupport implements MockMvcBuilder { private final WebApplicationContext webAppContext; @@ -54,6 +55,8 @@ public class DefaultMockMvcBuilder extends MockMvcB private final List globalResultHandlers = new ArrayList(); + private Boolean dispatchOptions = Boolean.FALSE; + /** * Protected constructor. Not intended for direct instantiation. @@ -178,6 +181,17 @@ public class DefaultMockMvcBuilder extends MockMvcB return (T) this; } + /** + * 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; + } + /** * 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/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 b9597c196e8..079a42fc012 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. 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 00000000000..b3f42091ef4 --- /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()); + } + } + +} 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 00000000000..32713e951c7 --- /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(); + } + } + + +} 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 00000000000..e73e3dd4c33 --- /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 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 80a0d138f34..568f765564a 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/plain")) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)); } @Test 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 00000000000..101285c5201 --- /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 { + } +} 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 441a53e4ce4..0d29289c77e 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. @@ -30,12 +30,12 @@ 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; import java.util.Map; import java.util.Set; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -97,8 +97,10 @@ public class MockHttpServletRequest implements HttpServletRequest { private static final String CHARSET_PREFIX = "charset="; + private boolean active = true; + // --------------------------------------------------------------------- // ServletRequest properties // --------------------------------------------------------------------- @@ -140,6 +142,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private int localPort = DEFAULT_SERVER_PORT; + // --------------------------------------------------------------------- // HttpServletRequest properties // --------------------------------------------------------------------- @@ -235,6 +238,7 @@ public class MockHttpServletRequest implements HttpServletRequest { this.locales.add(Locale.ENGLISH); } + // --------------------------------------------------------------------- // Lifecycle methods // --------------------------------------------------------------------- @@ -279,6 +283,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } } + // --------------------------------------------------------------------- // ServletRequest interface // --------------------------------------------------------------------- @@ -290,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() { @@ -351,7 +356,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 +378,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 +388,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 +400,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 +431,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 +441,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 +463,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 +472,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 +514,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 +579,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 +640,7 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.localPort; } + // --------------------------------------------------------------------- // HttpServletRequest interface // --------------------------------------------------------------------- @@ -797,8 +803,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/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index c86e95a93a7..75a7a1fc3ba 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/main/java/org/springframework/mock/web/MockHttpSession.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpSession.java index 1855230d2c5..548c2016d15 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 b492c1fa980..2c5d07e8e3c 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 562179ceac8..40fbabd1a17 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/MockClientDataRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java index 885c7996083..f6a850c7aa3 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 6dbaa70e321..7f5ad3fe962 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 ef3dc9d2c0a..34a6dea478c 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/MockPortletContext.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java index b1193ff5e1e..39dc9f5b294 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 70e90567b0c..38b517351a7 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 93800340b85..5eaec799063 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; } 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 5c965b85b86..8fe1e42cdcc 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/ContextLoaderUtils.java b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java index 47ee0c78cf0..8016c5d7c77 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, 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 d138484c8a7..c67f0c72d75 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-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 0928ff4c9ec..0fc6c6012c7 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 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 01302bb1100..b87c987dacd 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); 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 532a82c01fb..383b20dff90 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; @@ -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, Integer.class); } /** @@ -82,7 +83,7 @@ public class JdbcTestUtils { if (StringUtils.hasText(whereClause)) { sql += " WHERE " + whereClause; } - return jdbcTemplate.queryForInt(sql); + return jdbcTemplate.queryForObject(sql, Integer.class); } /** @@ -103,6 +104,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 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} + * 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/main/java/org/springframework/test/jpa/AbstractJpaTests.java b/spring-test/src/main/java/org/springframework/test/jpa/AbstractJpaTests.java index ba959d162f2..005c19e3d84 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-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 194e0037973..00000000000 --- 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/INestedTestBean.java b/spring-test/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 cd1724f2645..00000000000 --- 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 412891c439b..00000000000 --- 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 3ce93f7c439..00000000000 --- 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/mock/web/MockHttpServletRequestTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java index 085bbb8b7db..a237bb00d1e 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-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index c16f7cab9e3..867b86ad90a 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-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java b/spring-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java index 06c94aa4417..ba8c81c2945 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 307a4e93df2..7b96503a3fe 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 72360454848..b1939de12fd 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/ClassLevelDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java index 3768b03cb63..0be28a871e1 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. @@ -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; @@ -37,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. @@ -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/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties index 1efbb6201e0..45d36076bba 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 eb6f44f176a..3a976747ea7 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 1efbb6201e0..45d36076bba 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 81f51d459a9..77f079aec24 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 acdab7073c1..9f2fdef412d 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 147679ed5f1..735f96a01f6 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 a219470ce63..a91178410a2 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 bab1df5ff8d..c88aed37d12 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 0c068820875..3ee77974a0e 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 2f6eda6962f..b40fed69ca8 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 cb75b8accd4..f6a90a62eac 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 62206fde4a8..67590a6b584 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 ed2f58de118..bf07919721b 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 0e62ef734fc..6df81585fb4 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 d41dbb50269..b5d74839f68 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/RepeatedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java index 49d5ad5e7a4..6b7241261be 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. @@ -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/SpringJUnit4ClassRunnerAppCtxTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml index dffdb30f99b..704b3478733 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 399f6a61030..4973d7c68de 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/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 2f293d88475..72ddd1b8c4f 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 a3679ba75e1..3877058b00e 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. @@ -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(); @@ -64,34 +67,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 = 200) - public void testJUnitTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + @Test(timeout = 10) + public void jUnitTimeoutWithSleep() throws Exception { + Thread.sleep(20); } // Should Fail due to timeout. @Test - @Timed(millis = 200) - public void testSpringTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + @Timed(millis = 10) + 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 */ } } 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 46dfd6725a6..a0c51ded527 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 469e35f8d9d..e8a440a230a 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 e426d1e7f3b..05c74a29eb7 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 9f29d9a54aa..7af6a541b45 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 278804817e4..00da19f130c 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 3cf8f064d0c..9b4793e462f 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 b54613b4910..6613a695b4a 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 c060ea4b555..a0f7668ae2f 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 a3d2ecee168..7da5e68bd01 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 54596ae6d29..cca20f48278 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 0208925227c..19eefe388ae 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 cc26b849dbb..836dca41df5 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 98cc3af1495..44b5675a89a 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 9fb695889ae..cafc8b6e475 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 f6f2907f875..07a8d2d5ffc 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 a4af38435a4..818212dd3e1 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 8427a674a3d..3861d0ec592 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 1fc6d4ecfc9..0e672de0843 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 f79a9b0aa5d..1ed4f5467a4 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 55a4cff1e8a..7238260bd43 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 2f6eda6962f..b40fed69ca8 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 fb373a03479..7131201d438 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 cb75b8accd4..f6a90a62eac 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 9896e35880b..1f488ec26c6 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 1c9fbe91255..cd81b6becb8 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 5c99fefa39f..b01764251c8 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 d8b7fcacf3f..59cef2c1dbe 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; @@ -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) { 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 373166d9b41..6e0f84f7339 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 3f6a054ecb0..622f0dfe682 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 cd20e40f3f5..5dbba76acbd 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 72af7e7a7bc..78720a8f5ec 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 6f1525229fd..331342d4fcc 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 d8c070c5043..76a82b823c2 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 bbc0951e4fc..8492b02d5a6 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 b9d6b4b6aef..363d47a9b27 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 b7a52aa961b..957533f9130 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 4cfb6b8abc4..f20e466410f 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 11e92153da0..a46a6da3d1f 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 0ad8862c2ed..ee25cb32e45 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/testng/FailingBeforeAndAfterMethodsTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/FailingBeforeAndAfterMethodsTests.java index 05ba435f9b3..74e8f2513ad 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 dfbdc9ad831..00000000000 --- 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. 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 c07b25a9273..829d70ffec5 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/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java index d5fd1b68e4b..6ebdf918192 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)); + } + + } 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 0930460eeaa..7f2a6c5b232 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/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java b/spring-tx/src/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java index 25bac956685..41bf5447278 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()); + } + } 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 fac5eba990c..61f8db5b4e4 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") 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 8d15342c02d..bcd2c778805 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. @@ -16,25 +16,24 @@ 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.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; 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. @@ -233,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. */ @@ -247,32 +330,11 @@ 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); } } - /** - * 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 @@ -303,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 @@ -533,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 11f72759a7f..db46387077c 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(); - } - } - } 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 eaf963cc397..62b408e155c 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) { 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 a992a2ebfc6..00000000000 --- 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 c5360de5316..00000000000 --- 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 ddb091770ee..00000000000 --- 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 412891c439b..00000000000 --- 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 6d71de75764..00000000000 --- 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 c7066b5cc7f..00000000000 --- 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 4e1641b2cd8..00000000000 --- 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 13f3b5d360d..d3852d4e34a 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 e2066af4d92..eb68f255173 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 b1862dd8937..00000000000 --- 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 11566aeee71..04e937b7ecc 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 8bb61812009..c13ea6bc417 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 38c7e20d224..3f4286e51b9 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 7808f43b991..813a905e079 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 7caafe92c21..ad05997a079 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 21c5f5374fb..556cb599659 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 0f0deca8663..92f1ed65142 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 417859b43ec..5c11e26d5dd 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 d30fd87be1a..bd659fd8934 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 d6a79128d0f..ee458c0cf84 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 11a649ad50d..965a0db01e0 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 ea4f7189c83..a707e84fd36 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 7a818f701be..0a49a21b636 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; @@ -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 a34a228a456..1dda314ddad 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; @@ -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-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java index 302026a7aaa..79885dd3ee3 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 09c860fffd5..e9ef193b449 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 12c70ed91c2..5630bd82197 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 99f791a5328..ff819d3ede5 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 0a4b7e9f1c5..a8adf10c6df 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 dbe6421093e..00000000000 --- 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/main/java/org/springframework/http/HttpStatus.java b/spring-web/src/main/java/org/springframework/http/HttpStatus.java index 74dc2af2c21..225fbccd9f7 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}. 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 00000000000..358c9c8226a --- /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 99e1b2d1249..9f527c7c8ce 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/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java index ba482f31344..bb878444201 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-2012 the original author or authors. + * Copyright 2002-2013 the original author 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 f280790fec8..f075b202bd5 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/CommonsClientHttpResponse.java b/spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpResponse.java index 7cc8cec6e93..0e3f949da39 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/client/InterceptingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java index 9d397604799..a422614fe9f 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/SimpleBufferingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java index 56eaf1af85e..c2a78642964 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-2012 the original author or authors. + * Copyright 2002-2013 the original author 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 22d17b50f0b..3aa31d9b839 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 a5e831102c4..f14f7e9025d 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. @@ -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,18 +70,20 @@ 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(); this.body = this.connection.getOutputStream(); } - return new NonClosingOutputStream(this.body); + return StreamUtils.nonClosing(this.body); } private void writeHeaders(HttpHeaders headers) { @@ -106,26 +112,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/BufferedImageHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java index d9bec7b4773..74c1772558b 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-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,7 +132,7 @@ public class BufferedImageHttpMessageConverter implements HttpMessageConverter imageWriters = ImageIO.getImageWritersByMIMEType(mediaType.toString()); @@ -191,7 +191,7 @@ public class BufferedImageHttpMessageConverter implements HttpMessageConverter= 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 c97e05f63b1..516eb92ab25 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-2012 the original author or authors. + * Copyright 2002-2013 the original author 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) @@ -265,10 +264,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/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java index 9991fbcc804..69f22a92e10 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 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 8cf79f927d4..a5d0357d91e 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; - } - } 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 7f469a43185..6af1c621dea 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 9d094d75d32..47d2a567277 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; 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 ff4849e35e2..320bb95d133 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-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 43032ba5981..b1395b49852 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; 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 fe7fac62cd4..69ec8011031 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 03f13d86ff6..e37776a3c87 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/context/ConfigurableWebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java index a6185a81e8f..cba5e1dbc30 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 6afd42b16c7..69d812da378 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; @@ -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; @@ -280,7 +281,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 +345,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 +380,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 +478,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 " + @@ -485,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/request/async/DeferredResult.java b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java index 4da20dd40b1..22ea83f4585 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 2e104d8e75b..8c79b4230f2 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 15cfdc96eeb..59fa985acb7 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-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 f36bddc3168..92b1f7907a7 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 ac87960cd00..d30d3aef841 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 5de71bda608..5d26a434e3c 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-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java index 4d93eff7f2c..fc43fc5f8b5 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 07c44b32a88..cd14b2e3aec 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/AbstractNamedValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java index 9e35288687c..a5154792101 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/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java index 92a2aa88d13..d93a6d43a3b 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 ee5672cfa44..7366edef120 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 e7b46bdb6a9..7e4fdb40367 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 3f351595ecd..2a532f4bed8 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 e2a7b7d7982..b3c34427910 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 d97fe876d19..ae1afc1155f 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-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index f3a5ec9013b..60e67878b3f 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. @@ -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; @@ -38,9 +39,11 @@ 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 */ +@SuppressWarnings("serial") final class HierarchicalUriComponents extends UriComponents { private static final char PATH_DELIMITER = '/'; @@ -405,7 +408,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()); @@ -425,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 @@ -614,7 +607,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/main/java/org/springframework/web/util/JavaScriptUtils.java b/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java index b28d398687f..861b46fe55b 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,27 @@ 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 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/main/java/org/springframework/web/util/Log4jWebConfigurer.java b/spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java index 63211beaf5b..8b50ac6fda1 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/OpaqueUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java index d896518b29a..54d788d624e 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,9 +30,11 @@ 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 */ +@SuppressWarnings("serial") final class OpaqueUriComponents extends UriComponents { private static final MultiValueMap QUERY_PARAMS_NONE = new LinkedMultiValueMap(0); @@ -144,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/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 00000000000..46105f8aa03 --- /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/main/java/org/springframework/web/util/UriComponents.java b/spring-web/src/main/java/org/springframework/web/util/UriComponents.java index f04c5f695bd..2a2b300bfa6 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"; 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 141cd7b86e2..30dcac0f843 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. @@ -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) @@ -53,7 +55,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 = "([^:/?#]+):"; @@ -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; } @@ -496,8 +492,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 { @@ -588,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/main/java/org/springframework/web/util/UriTemplate.java b/spring-web/src/main/java/org/springframework/web/util/UriTemplate.java index a8699042e97..3aacd605592 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/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 67b7a4c024f..362b9336580 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. @@ -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; /** @@ -439,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) { @@ -491,6 +491,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-web/src/main/resources/META-INF/web-fragment.xml b/spring-web/src/main/resources/META-INF/web-fragment.xml index d7c28cbccdb..e687c8b58ec 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 + 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 bb5e71f5cd0..00000000000 --- 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 a992a2ebfc6..00000000000 --- 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 c5360de5316..00000000000 --- 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 61f911902c7..00000000000 --- 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 ddb091770ee..00000000000 --- 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 412891c439b..00000000000 --- 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 dbe365f4937..00000000000 --- 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 1fc36aba374..00000000000 --- 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 6fc7e36aa90..00000000000 --- 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/MediaTypeTests.java b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java index 906c8dec588..d5657d199e7 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=\""); } diff --git a/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java b/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java index c8dfbfc079b..9939aaf0349 100644 --- a/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java +++ b/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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.http; +import static org.mockito.Mockito.spy; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -28,7 +30,7 @@ public class MockHttpOutputMessage implements HttpOutputMessage { private final HttpHeaders headers = new HttpHeaders(); - private final ByteArrayOutputStream body = new ByteArrayOutputStream(); + private final ByteArrayOutputStream body = spy(new ByteArrayOutputStream()); @Override public HttpHeaders getHeaders() { 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 2af35321ff6..3a3d4a68851 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 83add2ceaff..00000000000 --- 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/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java new file mode 100644 index 00000000000..002f33c7e8e --- /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 00000000000..68111693e18 --- /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; + } +} 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 ccb91450a4a..6eed7ae1be6 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-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java index 3fd2d97e2af..0dcb8703bf9 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. @@ -51,6 +51,7 @@ public class BufferedImageHttpMessageConverterTests { public void canWrite() { assertTrue("Image not supported", converter.canWrite(BufferedImage.class, null)); assertTrue("Image not supported", converter.canWrite(BufferedImage.class, new MediaType("image", "png"))); + assertTrue("Image not supported", converter.canWrite(BufferedImage.class, new MediaType("*", "*"))); } @Test @@ -85,7 +86,7 @@ public class BufferedImageHttpMessageConverterTests { converter.setDefaultContentType(contentType); BufferedImage body = ImageIO.read(logo.getFile()); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); - converter.write(body, contentType, outputMessage); + converter.write(body, new MediaType("*", "*"), outputMessage); assertEquals("Invalid content type", contentType, outputMessage.getHeaders().getContentType()); assertTrue("Invalid size", outputMessage.getBodyAsBytes().length > 0); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); 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 2344269b634..0ea0462a504 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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,6 +45,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static org.junit.Assert.*; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; /** * @author Arjen Poutsma @@ -72,7 +74,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"); @@ -112,6 +113,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); @@ -157,6 +159,7 @@ public class FormHttpMessageConverterTests { item = (FileItem) items.get(4); assertEquals("xml", item.getFieldName()); assertEquals("text/xml", item.getContentType()); + verify(outputMessage.getBody(), never()).close(); } private static class MockHttpOutputMessageRequestContext implements RequestContext { 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 5694b666105..c5dc6d76010 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) { 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 6f52ab8e3e8..990026770db 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(); } 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 6617a787d52..d26b34565f1 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 71c463177a5..b436e306ecd 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-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java index 7ae30114dea..66637e04b25 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 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 83add2ceaff..9f5a3d9c339 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 dbe6421093e..00000000000 --- 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 9f6a1df756f..25d63e8b3a9 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 cf514b44b86..34340bd3e16 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/ServletRequestUtilsTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java index ada52ec33c2..334f4b0d78c 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(); 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 3f194e9bd0f..b3e347fd5fb 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 a02fcae95b9..ea09d9a3ddf 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 5c18203da6b..a4b7d6018ac 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 3b12ab2dbaf..6f88b6a9482 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 250e50c75c0..4a5703f34a0 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 c6b0c656fae..4e540a7d202 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 53e2e0a4583..5c2ef5823c0 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 1d383013423..8412e2b667c 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 a2c27162a25..053a53150ac 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/InitBinderDataBinderFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java index 40b600377cb..866fcae1add 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 986df7e9fa5..42c13d26712 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; @@ -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 +} 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 f8978d8b176..bda24d4892a 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) { } } 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 a9699262e48..1da19343914 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/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java index 29df40fbf33..b264a446136 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; 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 00000000000..182f18eb2db --- /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("<>")); + } + +} 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 00000000000..21082779a4c --- /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"); + } + } + +} 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 8205ca6cdf8..25fbb98d59e 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 { @@ -55,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(); @@ -312,4 +316,42 @@ 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")); + } + + @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")); + } + + @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")); + } } 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 c9f8d609177..2013e6df659 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. @@ -16,14 +16,24 @@ 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.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 @@ -75,4 +85,38 @@ 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())); + } + + @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))); + } + } 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 f2d06c527f4..3ed39dfd7aa 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 ee1313d4dc1..92759852b5b 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 e4f05b9abe5..e92f639f8ca 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 a992a2ebfc6..00000000000 --- 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 c5360de5316..00000000000 --- 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 ddb091770ee..00000000000 --- 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 412891c439b..00000000000 --- 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 6d71de75764..00000000000 --- 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 d6911ee72f5..00000000000 --- 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 855f23af396..00000000000 --- 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 6fc7e36aa90..00000000000 --- 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 013a65a0e49..00000000000 --- 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 b9a7925ad82..00000000000 --- 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 a7207435209..00000000000 --- 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 14acac1ceb9..37d4c9715fb 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 d580974a608..00000000000 --- 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 e8f5e91dfb6..00000000000 --- 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 5a2b7fd1aa8..00000000000 --- 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 82a89b61a38..00000000000 --- 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 7d154808d3c..00000000000 --- 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 e43172c1982..00000000000 --- 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 cf3e6e26c16..00000000000 --- 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 963ae040f27..da8aa73cac6 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 6cb7e3ae5f3..b1b1459ee75 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 46ea7b2ba04..fdb7d9df461 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 7bd390f9d29..3f53c7edfad 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 3f46ddd3a83..3bf24624893 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/bind/PortletRequestUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java index 8092d835b32..9c3e7b045de 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-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 8aeeb819b5d..bec09daa5e2 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 452ddb3c520..288b901f372 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 04bc32bb88d..9a4a2163138 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 4002703b211..85885f238d0 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 9ec0c1be3bb..2df278bba00 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 bad17962411..2ea777d8c40 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 4705be2f542..600dc7e8fa6 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 072476b61da..7a58b4a1c45 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 c291a8e74b1..8fd99d5357f 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-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 f01f25dd1ad..d23ac0033b2 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)); 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 df8cd2d4532..67dec591243 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; 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 ca2a919043e..a3f3c375478 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. @@ -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; @@ -39,11 +40,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 +641,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); @@ -861,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/main/java/org/springframework/web/servlet/HttpServletBean.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java index 044b56d2aea..bcd3a4d1606 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/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java index 9d409a3fec5..7fef39364c3 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/AsyncSupportConfigurer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java index 07d2b1a87e5..53e4893f99e 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 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 6b6f5d1acf8..7e85dcf956e 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 96fdcaf4e09..65ef9be6c53 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 fcc284989f8..adfd5cf1632 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/WebMvcConfigurationSupport.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java index e85f1891260..c3d1fc08833 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/config/annotation/WebMvcConfigurerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java index ac63b1cbca9..6f6c82733c0 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/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java index ea079c49386..b790a1e62b2 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 28fbe1efbc7..ccdec77d51d 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 @@ -165,25 +172,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 +193,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. */ 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 0d58e8c134c..3e5fd736592 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/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 15aee22ec25..bc65b27de2a 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/condition/PatternsRequestCondition.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java index 16b9743b2b9..04c5821cc98 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/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 dfdfc05ed25..89fcb4e9e1c 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. @@ -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; /** @@ -100,7 +104,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 +117,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 +140,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; } @@ -182,26 +189,38 @@ 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()) { 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)); } 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; } @@ -227,4 +246,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/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 ccdf7d3703e..48cff20fe54 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); 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 e93029aa640..edb113e6079 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( 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 52af8e427af..514df910022 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 d93b7746a7a..7b960f001ce 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 d79a9ef5db0..848e9127034 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/RequestMappingHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java index 315cf8f68e8..bb9ddd72b1f 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,15 +152,15 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi * Return the file extensions to use for suffix pattern matching. */ public List getFileExtensions() { - return fileExtensions; + return this.fileExtensions; } @Override public void afterPropertiesSet() { - super.afterPropertiesSet(); if (this.useRegisteredSuffixPatternMatch) { this.fileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); } + super.afterPropertiesSet(); } /** @@ -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/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 9b320cedb96..a7473a60f18 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 8d3d77acd99..48080aa16a0 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 3b54676ed31..3cfd087e334 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 5513dddae00..d716a9bc488 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/mvc/multiaction/ParameterMethodNameResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java index bd9405b65bb..1a2e175fb1a 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/support/AbstractDispatcherServletInitializer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java index ae16bdb9946..d6e6d010539 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()); 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 3f586a94467..cf33995355d 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. @@ -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; @@ -61,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 @@ -233,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() */ @@ -249,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() { @@ -309,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) { @@ -350,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"); @@ -359,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; @@ -376,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 */ @@ -422,22 +428,22 @@ 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; } /** * 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 @@ -573,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 @@ -584,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 @@ -596,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 @@ -609,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 @@ -620,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 @@ -632,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 @@ -644,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/support/ServletUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java index 8aa58643900..7ad0d49b78d 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/main/java/org/springframework/web/servlet/support/WebContentGenerator.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java index 7f759e8c97f..ec1cf27cc30 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); 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 f827631d62e..1af5e3972f5 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. @@ -50,6 +50,7 @@ import org.springframework.web.util.HtmlUtils; * @author Rob Harrop * @author Juergen Hoeller * @author Scott Andrews + * @author Rossen Stoyanchev * @since 2.0 * @see org.springframework.web.servlet.mvc.SimpleFormController */ @@ -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); } @@ -469,8 +474,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/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java index c0a66c52160..51b6cbc2f2f 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(); } } 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 2d543941af6..f7b59c3f6c2 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(); 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 2726e0537c3..77c3a67e036 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) { 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 43b29af322e..bfb41221f7c 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/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 f8297f3b144..b93a28269be 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 +} 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 7510ab304e6..29c670a1389 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 5b97da49a82..ef0ad59d995 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); + } + } 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 a992a2ebfc6..00000000000 --- 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/CustomEnum.java b/spring-webmvc/src/test/java/org/springframework/beans/CustomEnum.java deleted file mode 100644 index 1e43492191b..00000000000 --- a/spring-webmvc/src/test/java/org/springframework/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 org.springframework.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-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 c5360de5316..00000000000 --- 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 00dd127e47c..00000000000 --- 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 e0ae5f20a3f..00000000000 --- 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 d7fb346185a..00000000000 --- 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 cdf5ef510dd..00000000000 --- 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 ddb091770ee..00000000000 --- 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 412891c439b..00000000000 --- 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 7c66f4b451b..00000000000 --- 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 35d9c736c13..00000000000 --- 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 6d71de75764..00000000000 --- 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 6fc7e36aa90..00000000000 --- 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 013a65a0e49..00000000000 --- 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 b9a7925ad82..00000000000 --- 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 14acac1ceb9..37d4c9715fb 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/ProductBean.java b/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/ProductBean.java deleted file mode 100644 index 070fa2dc426..00000000000 --- 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 9ae4f54ec24..00000000000 --- 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 facc86bace1..00000000000 --- 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 e51cb8d151a..00000000000 --- 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 2b089f87482..00000000000 --- 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 a84b83f7ad6..15a7e36fea4 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 b9710dd7980..00000000000 --- 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 e25d3317379..6080b76eb0a 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 3a59552ded2..b4d7c366f24 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 2e4938383be..5f178d50ebb 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/empty-servlet.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/empty-servlet.xml deleted file mode 100644 index b49584e11dd..00000000000 --- 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 7da590d1f21..00000000000 --- 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/context/WEB-INF/test-servlet.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/test-servlet.xml index 4002703b211..85885f238d0 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 dd10e5fcab7..89c42365d4a 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 3423fd8e884..4dce1e9fac3 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 9e0784f2519..77bc44cca56 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; @@ -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; 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 1e44c2f8156..b5b4f0206fa 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 287ea086eb4..667fb643b4b 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. @@ -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.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,11 @@ 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.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -836,14 +835,14 @@ 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 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) { } @@ -860,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")); } 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 dbbb25fe5a9..ce525f937da 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/complexviews.properties b/spring-webmvc/src/test/java/org/springframework/web/servlet/complexviews.properties deleted file mode 100644 index 6917be21627..00000000000 --- 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 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 1c270ae5716..40f10ea7e60 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 ea1b09ed217..ff3ebd962f4 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 4749c85df72..da2da2e174a 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 d62174ab265..3c40caacd6b 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 705ac4ea815..1d37caff853 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/ResponseStatusExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java index 684550e18d3..4731ce6fedd 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(); + 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 { + + } + } 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 05e0f3c2a51..722099df3e2 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. @@ -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.beans.DerivedTestBean; -import org.springframework.beans.GenericBean; -import org.springframework.beans.ITestBean; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; -import org.springframework.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 @@ -329,7 +337,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 @@ -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/mvc/condition/PatternsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java index 9c38b7c39c4..72f6639713f 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 e0764f7e7bc..099197c07de 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. @@ -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; @@ -89,7 +90,6 @@ public class RequestMappingInfoHandlerMappingTests { this.handlerMapping = new TestRequestMappingInfoHandlerMapping(); this.handlerMapping.registerHandler(testController); - this.handlerMapping.setRemoveSemicolonContent(false); } @Test @@ -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"); @@ -202,6 +215,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}"); @@ -310,48 +336,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); @@ -399,6 +440,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 ""; 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 32ac81d6687..33307032e58 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 54d187f91a1..e0a515c3b05 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 450315e6de4..caa7fbcea66 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/RequestMappingHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java index b5a6bd139e5..63fce21fa7d 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. @@ -15,19 +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}. @@ -62,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()); @@ -78,4 +116,27 @@ 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); + } + + + @Controller + static class TestController { + + @RequestMapping + public void handle() { + } + } + } 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 3d77c292373..a15466aabc0 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 21ef1b19592..26e95d0c33d 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 e42ccb29693..6c5c7327e08 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 18ae25f7e01..de40940d0d2 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; @@ -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/mvc/support/DefaultHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java index 852c95fd8af..fe492bab941 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 8a0518c5607..cb7b41e9d69 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/support/ServletUriComponentsBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java index d87212008c9..02ee04662d1 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"); 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 98764500996..4af3a47cde6 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/UrlTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java index edabd11d4fb..f66a8c2b507 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/tags/form/AbstractFormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractFormTagTests.java index e380397ed48..f1b27c493ed 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 1d299c222ad..b471438f1e6 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 70aae8f0e49..657aab3c24a 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 055580d5a34..9ffeefbf2ca 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 6e11e063319..a36012bb60e 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/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index 3bd879a1eac..3f4247033b5 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. @@ -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 { @@ -166,6 +167,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}"); @@ -293,7 +338,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests { String output = getOutput(); - assertEquals("", getInputTag(output)); + assertEquals("", getInputTag(output)); assertFormTagOpened(output); assertFormTagClosed(output); 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 60beaccb6d1..613196224c0 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 7ca869480b1..52ba57f9f27 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 5654062ff7d..23b9016c747 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 7144652045e..aa853b99bfa 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 3acacbb8b8d..1d554f5ef4f 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 92290c23cc9..964e2d412f5 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 bcb5eeebaff..42190d39f82 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 93f6a04080a..702e790c9a3 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 8786a091fae..8dfc3e3e0cf 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 e1a6a313d0d..4ea337bbd75 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 4684b5b659a..bfa9bd8dbe1 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 d252550f18a..d3c45fb2493 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/ResourceBundleViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java index b100a6a68eb..19e4551fb3d 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/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 fadc6063737..3836559480d 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/FreeMarkerConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java index 962b3fa33c3..077c5b3a73a 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/freemarker/FreeMarkerMacroTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java index d3af0683f4f..9e4f320ef68 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; @@ -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 8440b4f945f..b1e01561861 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" /> 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 69f8ea613aa..64750505975 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())); } 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 3ed42765505..04c8497df3c 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 ff477a97f4b..b07a53716ea 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 7da590d1f21..eb7bf0f6eae 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/api/stylesheet.css b/src/api/stylesheet.css new file mode 100644 index 00000000000..4b105f4ca41 --- /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; +} diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index b9726400ae4..1e6da7b4efe 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -3,14 +3,93 @@ SPRING FRAMEWORK CHANGELOG http://www.springsource.org +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) +* "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) +* 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) +* 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) +* 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) + + 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) +* 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) +* 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) +* 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 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) +* 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) * 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) +* 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) Changes in version 3.2 GA (2012-12-13) diff --git a/src/dist/readme.txt b/src/dist/readme.txt index e55fefae193..c58486a587d 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. diff --git a/src/eclipse/org.eclipse.jdt.core.prefs b/src/eclipse/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000000..80a095b1a1a --- /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.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 +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.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.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 +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.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.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.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.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 +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.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 +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 00000000000..7631dce007a --- /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=1 +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 00000000000..ce05d97c85e --- /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 00000000000..e4a5a385a27 --- /dev/null +++ b/src/eclipse/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/reference/docbook/aop-api.xml b/src/reference/docbook/aop-api.xml index 4099fbc940e..a616d7b30d1 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.
    diff --git a/src/reference/docbook/aop.xml b/src/reference/docbook/aop.xml index 7078e1535aa..fafebe61276 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 @@ -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 diff --git a/src/reference/docbook/beans-customizing.xml b/src/reference/docbook/beans-customizing.xml index acca5514a74..9e5c4284b98 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 diff --git a/src/reference/docbook/beans-dependencies.xml b/src/reference/docbook/beans-dependencies.xml index 0723be50fc2..7c098412902 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.
    diff --git a/src/reference/docbook/beans-extension-points.xml b/src/reference/docbook/beans-extension-points.xml index 551496d7bea..d2a0aa80c34 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 diff --git a/src/reference/docbook/cache.xml b/src/reference/docbook/cache.xml index b96eaa3c917..01fa2d5a875 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.
    @@ -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 + @@ -544,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 @@ -570,10 +592,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. diff --git a/src/reference/docbook/cci.xml b/src/reference/docbook/cci.xml index e5fc3bb82f9..051d587da5b 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"> diff --git a/src/reference/docbook/index.xml b/src/reference/docbook/index.xml index 393858cecda..de4af30072f 100644 --- a/src/reference/docbook/index.xml +++ b/src/reference/docbook/index.xml @@ -471,6 +471,9 @@ + + diff --git a/src/reference/docbook/jdbc.xml b/src/reference/docbook/jdbc.xml index e3b3d7f03c4..f4af0e3b233 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 diff --git a/src/reference/docbook/jmx.xml b/src/reference/docbook/jmx.xml index 85ae5d0d271..05e8588ebfa 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"/> ]]> diff --git a/src/reference/docbook/migration-3.1.xml b/src/reference/docbook/migration-3.1.xml new file mode 100644 index 00000000000..15ca8d49798 --- /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/migration-3.2.xml b/src/reference/docbook/migration-3.2.xml index c96b43d8ba1..79f5c9150c4 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.
    diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index ffe081c1e09..a9e8489af34 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.
    @@ -1055,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) { // ... } @@ -1073,6 +1080,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 @@ -2138,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>>. +
    @@ -2575,7 +2602,7 @@ deferredResult.setResult(data); ... - <web-app> + </web-app> The DispatcherServlet and any @@ -5091,7 +5118,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { - configurer.setFavorPathExtension(false).setFavorParameter(true); + configurer.favorPathExtension(false).favorParameter(true); } } diff --git a/src/reference/docbook/new-in-3.1.xml b/src/reference/docbook/new-in-3.1.xml index ef69b647d06..8a56bfd6472 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 diff --git a/src/reference/docbook/new-in-3.2.xml b/src/reference/docbook/new-in-3.2.xml index 1f3d04e3ba4..8d403c6ead9 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. @@ -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. diff --git a/src/reference/docbook/overview.xml b/src/reference/docbook/overview.xml index a4de366ef8c..9bef8ee488e 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 diff --git a/src/reference/docbook/oxm.xml b/src/reference/docbook/oxm.xml index f5797b2c4b8..1a7cbac17c5 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 @@ -438,7 +441,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 +465,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 @@ -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 + + + + + +
    diff --git a/src/reference/docbook/remoting.xml b/src/reference/docbook/remoting.xml index 4bd5acc920d..f642f9d653b 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 diff --git a/src/reference/docbook/scheduling.xml b/src/reference/docbook/scheduling.xml index 6c5b7fbe83c..a30a0f7d998 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 * * ?" /> diff --git a/src/reference/docbook/validation.xml b/src/reference/docbook/validation.xml index 5ad3faeee8a..2eb98a76b02 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: + + +
    diff --git a/src/reference/docbook/xsd-configuration.xml b/src/reference/docbook/xsd-configuration.xml index f57e766e067..a78556a27c8 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'.
    diff --git a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java b/src/test/java/com/foo/Component.java similarity index 57% rename from spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java rename to src/test/java/com/foo/Component.java index 3d0bce4c841..759954c41db 100644 --- a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java +++ b/src/test/java/com/foo/Component.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. @@ -14,35 +14,22 @@ * limitations under the License. */ -package org.springframework.ui.jasperreports; +package com.foo; -/** - * @author Rob Harrop - */ -public class PersonBean { - - private int id; +import java.util.ArrayList; +import java.util.List; +public class Component { private String name; + private List components = new ArrayList(); - private String street; - - private String city; - - public String getCity() { - return city; + // mmm, there is no setter method for the 'components' + public void addComponent(Component component) { + this.components.add(component); } - public void setCity(String city) { - this.city = city; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; + public List getComponents() { + return components; } public String getName() { @@ -52,13 +39,4 @@ public class PersonBean { 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-beans/src/test/java/com/foo/ComponentBeanDefinitionParser.java b/src/test/java/com/foo/ComponentBeanDefinitionParser.java similarity index 75% rename from spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParser.java rename to src/test/java/com/foo/ComponentBeanDefinitionParser.java index 94dd439bfb0..9fb2213c2bb 100644 --- a/spring-beans/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/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java similarity index 91% rename from spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java rename to src/test/java/com/foo/ComponentBeanDefinitionParserTests.java index a7a38f2c480..4a036f6c27f 100644 --- a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java +++ b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author 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 com.foo; import static org.hamcrest.CoreMatchers.equalTo; @@ -30,15 +31,14 @@ import org.springframework.core.io.ClassPathResource; /** * @author Costin Leau */ -public class ComponentBeanDefinitionParserTest { +public class ComponentBeanDefinitionParserTests { private static DefaultListableBeanFactory bf; @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/com/foo/ComponentFactoryBean.java b/src/test/java/com/foo/ComponentFactoryBean.java similarity index 55% rename from spring-beans/src/test/java/com/foo/ComponentFactoryBean.java rename to src/test/java/com/foo/ComponentFactoryBean.java index ac47c4efea9..2b126d4f4e5 100644 --- a/spring-beans/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/spring-test/src/test/java/org/springframework/beans/Employee.java b/src/test/java/com/foo/ComponentNamespaceHandler.java similarity index 63% rename from spring-test/src/test/java/org/springframework/beans/Employee.java rename to src/test/java/com/foo/ComponentNamespaceHandler.java index 9289e451370..b1a830c83b7 100644 --- a/spring-test/src/test/java/org/springframework/beans/Employee.java +++ b/src/test/java/com/foo/ComponentNamespaceHandler.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,25 +14,14 @@ * limitations under the License. */ -package org.springframework.beans; +package com.foo; -public class Employee extends TestBean { +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; - private String co; - - /** - * Constructor for Employee. - */ - public Employee() { - super(); +public class ComponentNamespaceHandler extends NamespaceHandlerSupport { + @Override + public void init() { + registerBeanDefinitionParser("component", + new ComponentBeanDefinitionParser()); } - - public String getCompany() { - return co; - } - - public void setCompany(String co) { - this.co = co; - } - } 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 4be55f0ea74..49e480a6644 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 7472033a36b..067a3351662 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; @@ -39,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-context.xml b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests-context.xml index 4f9a0361c04..c5b04a53df3 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 74ff0825e65..a972be2d97f 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,22 +32,19 @@ 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 * 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 @@ -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/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java b/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java index b213a2a4e0f..5f5938ed364 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")); } diff --git a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java index fae32ac8f52..aca10a3fb26 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 ff94b0dd222..00000000000 --- 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 d4f33e642e8..54511e7e7b4 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 a8a3a01e3a3..00000000000 --- 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 5aa37b61e14..00000000000 --- 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 533d0df36e3..00000000000 --- 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/ITestBean.java b/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 0434b6ad114..00000000000 --- 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 160681e5565..00000000000 --- 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 c6d1acd27b5..00000000000 --- 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 f81ac4f0921..00000000000 --- 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 b76f12a75e8..00000000000 --- 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 b1cdf832a4a..00000000000 --- 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 d2fbdc584af..00000000000 --- 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 e9bc9fee04a..00000000000 --- 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()); - } - -} 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