Compare commits

..

1 Commits

Author SHA1 Message Date
Spring Buildmaster f9b6e94e00 Release v5.3.9 2021-07-14 06:36:18 +00:00
236 changed files with 3216 additions and 4785 deletions
+44 -52
View File
@@ -1,16 +1,16 @@
plugins {
id 'io.spring.dependency-management' version '1.0.11.RELEASE' apply false
id 'io.spring.nohttp' version '0.0.10'
id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false
id 'org.jetbrains.dokka' version '1.5.0' apply false
id 'org.asciidoctor.jvm.convert' version '3.3.2'
id 'org.asciidoctor.jvm.pdf' version '3.3.2'
id 'de.undercouch.download' version '4.1.2'
id "io.freefair.aspectj" version '6.1.0' apply false
id "com.github.ben-manes.versions" version '0.39.0'
id "com.github.johnrengelman.shadow" version '7.0.0' apply false
id "me.champeau.jmh" version "0.6.6" apply false
id "org.jetbrains.kotlin.plugin.serialization" version "1.5.30" apply false
id 'io.spring.dependency-management' version '1.0.9.RELEASE' apply false
id 'io.spring.nohttp' version '0.0.5.RELEASE'
id 'org.jetbrains.kotlin.jvm' version '1.5.21' apply false
id 'org.jetbrains.dokka' version '0.10.1' apply false
id 'org.asciidoctor.jvm.convert' version '3.1.0'
id 'org.asciidoctor.jvm.pdf' version '3.1.0'
id 'de.undercouch.download' version '4.1.1'
id "io.freefair.aspectj" version '5.1.1' apply false
id "com.github.ben-manes.versions" version '0.28.0'
id "com.github.johnrengelman.shadow" version "6.1.0" apply false
id "me.champeau.jmh" version "0.6.4" apply false
id "org.jetbrains.kotlin.plugin.serialization" version "1.5.21" apply false
id "org.unbroken-dome.xjc" version '2.0.0' apply false
}
@@ -27,16 +27,16 @@ configure(allprojects) { project ->
dependencyManagement {
imports {
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.5"
mavenBom "io.netty:netty-bom:4.1.68.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.11"
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.4"
mavenBom "io.netty:netty-bom:4.1.65.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.9"
mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR10"
mavenBom "io.rsocket:rsocket-bom:1.1.1"
mavenBom "org.eclipse.jetty:jetty-bom:9.4.43.v20210629"
mavenBom "org.jetbrains.kotlin:kotlin-bom:1.5.30"
mavenBom "org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.5.2"
mavenBom "org.jetbrains.kotlinx:kotlinx-serialization-bom:1.2.2"
mavenBom "org.junit:junit-bom:5.8.0"
mavenBom "org.jetbrains.kotlin:kotlin-bom:1.5.21"
mavenBom "org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.5.1"
mavenBom "org.jetbrains.kotlinx:kotlinx-serialization-bom:1.2.1"
mavenBom "org.junit:junit-bom:5.7.2"
}
dependencies {
dependencySet(group: 'org.apache.logging.log4j', version: '2.14.1') {
@@ -67,8 +67,7 @@ configure(allprojects) { project ->
dependency "io.reactivex:rxjava:1.3.8"
dependency "io.reactivex:rxjava-reactive-streams:1.2.1"
dependency "io.reactivex.rxjava2:rxjava:2.2.21"
dependency "io.reactivex.rxjava3:rxjava:3.1.1"
dependency "io.smallrye.reactive:mutiny:1.0.0"
dependency "io.reactivex.rxjava3:rxjava:3.0.13"
dependency "io.projectreactor.tools:blockhound:1.0.4.RELEASE"
dependency "com.caucho:hessian:4.0.63"
@@ -76,10 +75,10 @@ configure(allprojects) { project ->
dependency("com.fasterxml.woodstox:woodstox-core:6.2.6") {
exclude group: "stax", name: "stax-api"
}
dependency "com.google.code.gson:gson:2.8.8"
dependency "com.google.code.gson:gson:2.8.7"
dependency "com.google.protobuf:protobuf-java-util:3.17.3"
dependency "com.googlecode.protobuf-java-format:protobuf-java-format:1.4"
dependency("com.thoughtworks.xstream:xstream:1.4.18") {
dependency("com.thoughtworks.xstream:xstream:1.4.17") {
exclude group: "xpp3", name: "xpp3_min"
exclude group: "xmlpull", name: "xmlpull"
}
@@ -128,18 +127,18 @@ configure(allprojects) { project ->
dependency "org.webjars:webjars-locator-core:0.47"
dependency "org.webjars:underscorejs:1.8.3"
dependencySet(group: 'org.apache.tomcat', version: '9.0.52') {
dependencySet(group: 'org.apache.tomcat', version: '9.0.50') {
entry 'tomcat-util'
entry('tomcat-websocket') {
exclude group: "org.apache.tomcat", name: "tomcat-websocket-api"
exclude group: "org.apache.tomcat", name: "tomcat-servlet-api"
}
}
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.52') {
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.50') {
entry 'tomcat-embed-core'
entry 'tomcat-embed-websocket'
}
dependencySet(group: 'io.undertow', version: '2.2.10.Final') {
dependencySet(group: 'io.undertow', version: '2.2.8.Final') {
entry 'undertow-core'
entry('undertow-websockets-jsr') {
exclude group: "org.jboss.spec.javax.websocket", name: "jboss-websocket-api_1.1_spec"
@@ -197,18 +196,18 @@ configure(allprojects) { project ->
exclude group: "org.hamcrest", name: "hamcrest-core"
}
}
dependencySet(group: 'org.mockito', version: '3.12.4') {
dependencySet(group: 'org.mockito', version: '3.11.0') {
entry('mockito-core') {
exclude group: "org.hamcrest", name: "hamcrest-core"
}
entry 'mockito-junit-jupiter'
}
dependency "io.mockk:mockk:1.12.0"
dependency "io.mockk:mockk:1.11.0"
dependency("net.sourceforge.htmlunit:htmlunit:2.52.0") {
dependency("net.sourceforge.htmlunit:htmlunit:2.51.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:htmlunit-driver:2.52.0") {
dependency("org.seleniumhq.selenium:htmlunit-driver:2.51.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:selenium-java:3.141.59") {
@@ -216,7 +215,7 @@ configure(allprojects) { project ->
exclude group: "io.netty", name: "netty"
}
dependency "org.skyscreamer:jsonassert:1.5.0"
dependency "com.jayway.jsonpath:json-path:2.6.0"
dependency "com.jayway.jsonpath:json-path:2.5.0"
dependency "org.bouncycastle:bcpkix-jdk15on:1.66"
dependencySet(group: 'org.apache.tiles', version: '3.0.8') {
@@ -313,8 +312,6 @@ configure([rootProject] + javaProjects) { project ->
pluginManager.withPlugin("kotlin") {
apply plugin: "org.jetbrains.dokka"
apply from: "${rootDir}/gradle/docs-dokka.gradle"
compileKotlin {
kotlinOptions {
languageVersion = "1.3"
@@ -339,25 +336,23 @@ configure([rootProject] + javaProjects) { project ->
}
checkstyle {
toolVersion = "8.45.1"
toolVersion = "8.44"
configDirectory.set(rootProject.file("src/checkstyle"))
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation("org.junit.jupiter:junit-jupiter-params")
testImplementation("org.junit.platform:junit-platform-suite-api")
testImplementation("org.mockito:mockito-core")
testImplementation("org.mockito:mockito-junit-jupiter")
testImplementation("io.mockk:mockk")
testImplementation("org.assertj:assertj-core")
testCompile("org.junit.jupiter:junit-jupiter-api")
testCompile("org.junit.jupiter:junit-jupiter-params")
testCompile("org.mockito:mockito-core")
testCompile("org.mockito:mockito-junit-jupiter")
testCompile("io.mockk:mockk")
testCompile("org.assertj:assertj-core")
// Pull in the latest JUnit 5 Launcher API to ensure proper support in IDEs.
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
testRuntimeOnly("org.junit.platform:junit-platform-suite-engine")
testRuntimeOnly("org.apache.logging.log4j:log4j-core")
testRuntimeOnly("org.apache.logging.log4j:log4j-slf4j-impl")
testRuntimeOnly("org.apache.logging.log4j:log4j-jul")
testRuntime("org.junit.platform:junit-platform-launcher")
testRuntime("org.junit.jupiter:junit-jupiter-engine")
testRuntime("org.apache.logging.log4j:log4j-core")
testRuntime("org.apache.logging.log4j:log4j-slf4j-impl")
testRuntime("org.apache.logging.log4j:log4j-jul")
// JSR-305 only used for non-required meta-annotations
compileOnly("com.google.code.findbugs:jsr305")
testCompileOnly("com.google.code.findbugs:jsr305")
@@ -368,7 +363,7 @@ configure([rootProject] + javaProjects) { project ->
"https://docs.oracle.com/javase/8/docs/api/",
"https://docs.oracle.com/javaee/7/api/",
"https://docs.oracle.com/cd/E13222_01/wls/docs90/javadocs/", // CommonJ
"https://www.ibm.com/docs/api/v1/content/SSEQTP_8.5.5/com.ibm.websphere.javadoc.doc/web/apidocs/",
"https://www.ibm.com/support/knowledgecenter/SS7JFU_8.5.5/com.ibm.websphere.javadoc.doc/web/apidocs/",
"https://glassfish.java.net/nonav/docs/v3/api/",
"https://docs.jboss.org/jbossas/javadoc/4.0.5/connector/",
"https://docs.jboss.org/jbossas/javadoc/7.1.2.Final/",
@@ -383,10 +378,7 @@ configure([rootProject] + javaProjects) { project ->
"https://hc.apache.org/httpcomponents-client-5.1.x/current/httpclient5/apidocs/",
"https://projectreactor.io/docs/test/release/api/",
"https://junit.org/junit4/javadoc/4.13.2/",
"https://junit.org/junit5/docs/5.8.0/api/",
"https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/",
"https://javadoc.io/static/io.rsocket/rsocket-core/1.1.1/",
"https://r2dbc.io/spec/0.8.5.RELEASE/api/"
"https://junit.org/junit5/docs/5.7.2/api/"
] as String[]
}
@@ -32,7 +32,6 @@ import org.gradle.api.tasks.compile.JavaCompile;
*
* @author Brian Clozel
* @author Sam Brannen
* @author Sebastien Deleuze
*/
public class CompilerConventionsPlugin implements Plugin<Project> {
@@ -44,8 +43,7 @@ public class CompilerConventionsPlugin implements Plugin<Project> {
List<String> commonCompilerArgs = Arrays.asList(
"-Xlint:serial", "-Xlint:cast", "-Xlint:classfile", "-Xlint:dep-ann",
"-Xlint:divzero", "-Xlint:empty", "-Xlint:finally", "-Xlint:overrides",
"-Xlint:path", "-Xlint:processing", "-Xlint:static", "-Xlint:try", "-Xlint:-options",
"-parameters"
"-Xlint:path", "-Xlint:processing", "-Xlint:static", "-Xlint:try", "-Xlint:-options"
);
COMPILER_ARGS = new ArrayList<>();
COMPILER_ARGS.addAll(commonCompilerArgs);
@@ -56,7 +54,7 @@ public class CompilerConventionsPlugin implements Plugin<Project> {
TEST_COMPILER_ARGS = new ArrayList<>();
TEST_COMPILER_ARGS.addAll(commonCompilerArgs);
TEST_COMPILER_ARGS.addAll(Arrays.asList("-Xlint:-varargs", "-Xlint:-fallthrough", "-Xlint:-rawtypes",
"-Xlint:-deprecation", "-Xlint:-unchecked"));
"-Xlint:-deprecation", "-Xlint:-unchecked", "-parameters"));
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,6 @@ package org.springframework.build.optional;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.attributes.Usage;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSetContainer;
@@ -29,7 +28,7 @@ import org.gradle.plugins.ide.eclipse.model.EclipseModel;
/**
* A {@code Plugin} that adds support for Maven-style optional dependencies. Creates a new
* {@code optional} configuration. The {@code optional} configuration is part of the
* project's compile and runtime classpaths but does not affect the classpath of
* project's compile and runtime classpath's but does not affect the classpath of
* dependent projects.
*
* @author Andy Wilkinson
@@ -44,16 +43,22 @@ public class OptionalDependenciesPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
Configuration optional = project.getConfigurations().create("optional");
optional.setCanBeConsumed(false);
optional.setCanBeResolved(false);
project.getPlugins().withType(JavaPlugin.class, (javaPlugin) -> {
SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class)
.getSourceSets();
SourceSetContainer sourceSets = project.getConvention()
.getPlugin(JavaPluginConvention.class).getSourceSets();
sourceSets.all((sourceSet) -> {
project.getConfigurations().getByName(sourceSet.getCompileClasspathConfigurationName()).extendsFrom(optional);
project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName()).extendsFrom(optional);
sourceSet.setCompileClasspath(
sourceSet.getCompileClasspath().plus(optional));
sourceSet.setRuntimeClasspath(
sourceSet.getRuntimeClasspath().plus(optional));
});
});
project.getPlugins().withType(EclipsePlugin.class, (eclipePlugin) -> {
project.getExtensions().getByType(EclipseModel.class)
.classpath((classpath) -> {
classpath.getPlusConfigurations().add(optional);
});
});
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ changelog:
- title: ":star: New Features"
labels:
- "type: enhancement"
- title: ":lady_beetle: Bug Fixes"
- title: ":beetle: Bug Fixes"
labels:
- "type: bug"
- "type: regression"
+2 -2
View File
@@ -1,4 +1,4 @@
FROM ubuntu:focal-20210827
FROM ubuntu:focal-20210119
ADD setup.sh /setup.sh
ADD get-jdk-url.sh /get-jdk-url.sh
@@ -6,6 +6,6 @@ RUN ./setup.sh java8
ENV JAVA_HOME /opt/openjdk/java8
ENV JDK11 /opt/openjdk/java11
ENV JDK16 /opt/openjdk/java16
ENV JDK15 /opt/openjdk/java15
ENV PATH $JAVA_HOME/bin:$PATH
+4 -4
View File
@@ -3,13 +3,13 @@ set -e
case "$1" in
java8)
echo "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u302-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u302b08.tar.gz"
echo "https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u282-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u282b08.tar.gz"
;;
java11)
echo "https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.12%2B7/OpenJDK11U-jdk_x64_linux_hotspot_11.0.12_7.tar.gz"
echo "https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.10%2B9/OpenJDK11U-jdk_x64_linux_hotspot_11.0.10_9.tar.gz"
;;
java16)
echo "https://github.com/adoptium/temurin16-binaries/releases/download/jdk-16.0.2%2B7/OpenJDK16U-jdk_x64_linux_hotspot_16.0.2_7.tar.gz"
java15)
echo "https://github.com/AdoptOpenJDK/openjdk15-binaries/releases/download/jdk-15.0.2%2B7/OpenJDK15U-jdk_x64_linux_hotspot_15.0.2_7.tar.gz"
;;
*)
echo $"Unknown java version"
+1 -1
View File
@@ -22,7 +22,7 @@ curl --output /opt/concourse-release-scripts.jar https://repo.spring.io/release/
mkdir -p /opt/openjdk
pushd /opt/openjdk > /dev/null
for jdk in java8 java11 java16
for jdk in java8 java11 java15
do
JDK_URL=$( /get-jdk-url.sh $jdk )
mkdir $jdk
+10 -10
View File
@@ -2,7 +2,7 @@ anchors:
git-repo-resource-source: &git-repo-resource-source
uri: ((github-repo))
username: ((github-username))
password: ((github-ci-release-token))
password: ((github-password))
branch: ((branch))
gradle-enterprise-task-params: &gradle-enterprise-task-params
GRADLE_ENTERPRISE_ACCESS_KEY: ((gradle_enterprise_secret_access_key))
@@ -45,7 +45,7 @@ resource_types:
type: registry-image
source:
repository: springio/artifactory-resource
tag: 0.0.17
tag: 0.0.13
- name: github-status-resource
type: registry-image
source:
@@ -119,14 +119,14 @@ resources:
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk11-build
- name: repo-status-jdk16-build
- name: repo-status-jdk15-build
type: github-status-resource
icon: eye-check-outline
source:
repository: ((github-repo-name))
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk16-build
context: jdk15-build
- name: slack-alert
type: slack-notification
icon: slack
@@ -244,7 +244,7 @@ jobs:
<<: *slack-fail-params
- put: repo-status-jdk11-build
params: { state: "success", commit: "git-repo" }
- name: jdk16-build
- name: jdk15-build
serial: true
public: true
plan:
@@ -252,7 +252,7 @@ jobs:
- get: git-repo
- get: every-morning
trigger: true
- put: repo-status-jdk16-build
- put: repo-status-jdk15-build
params: { state: "pending", commit: "git-repo" }
- do:
- task: check-project
@@ -265,12 +265,12 @@ jobs:
<<: *build-project-task-params
on_failure:
do:
- put: repo-status-jdk16-build
- put: repo-status-jdk15-build
params: { state: "failure", commit: "git-repo" }
- put: slack-alert
params:
<<: *slack-fail-params
- put: repo-status-jdk16-build
- put: repo-status-jdk15-build
params: { state: "success", commit: "git-repo" }
- name: build-pull-requests
serial: true
@@ -292,7 +292,7 @@ jobs:
privileged: true
timeout: ((task-timeout))
params:
BRANCH: ((branch))
<<: *build-project-task-params
on_success:
put: git-pull-request
params:
@@ -453,7 +453,7 @@ jobs:
groups:
- name: "builds"
jobs: ["build", "jdk11-build", "jdk16-build"]
jobs: ["build", "jdk11-build", "jdk15-build"]
- name: "releases"
jobs: ["stage-milestone", "stage-rc", "stage-release", "promote-milestone", "promote-rc", "promote-release", "create-github-release"]
- name: "ci-images"
+2 -2
View File
@@ -29,8 +29,8 @@ fi
echo "Staging $stageVersion (next version will be $nextVersion)"
sed -i "s/version=$snapshotVersion/version=$stageVersion/" gradle.properties
git config user.name "Spring Builds" > /dev/null
git config user.email "spring-builds@users.noreply.github.com" > /dev/null
git config user.name "Spring Buildmaster" > /dev/null
git config user.email "buildmaster@springframework.org" > /dev/null
git add gradle.properties > /dev/null
git commit -m"Release v$stageVersion" > /dev/null
git tag -a "v$stageVersion" -m"Release v$stageVersion" > /dev/null
+1 -1
View File
@@ -1,4 +1,4 @@
version=5.3.10
version=5.3.9
org.gradle.jvmargs=-Xmx1536M
org.gradle.caching=true
org.gradle.parallel=true
-30
View File
@@ -1,30 +0,0 @@
tasks.findByName("dokkaHtmlPartial")?.configure {
outputDirectory.set(new File(buildDir, "docs/kdoc"))
dokkaSourceSets {
configureEach {
sourceRoots.setFrom(file("src/main/kotlin"))
classpath.from(sourceSets["main"].runtimeClasspath)
externalDocumentationLink {
url.set(new URL("https://docs.spring.io/spring-framework/docs/current/javadoc-api/"))
}
externalDocumentationLink {
url.set(new URL("https://projectreactor.io/docs/core/release/api/"))
}
externalDocumentationLink {
url.set(new URL("https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/"))
}
externalDocumentationLink {
url.set(new URL("https://kotlin.github.io/kotlinx.coroutines/"))
}
externalDocumentationLink {
url.set(new URL("https://hamcrest.org/JavaHamcrest/javadoc/2.1/"))
}
externalDocumentationLink {
url.set(new URL("https://javadoc.io/doc/javax.servlet/javax.servlet-api/latest/"))
}
externalDocumentationLink {
url.set(new URL("https://javadoc.io/static/io.rsocket/rsocket-core/1.1.1/"))
}
}
}
}
+58 -11
View File
@@ -61,13 +61,57 @@ task api(type: Javadoc) {
/**
* Produce KDoc for all Spring Framework modules in "build/docs/kdoc"
*/
pluginManager.withPlugin("kotlin") {
tasks.dokkaHtmlMultiModule.configure {
dependsOn {
tasks.getByName("api")
dokka {
dependsOn {
tasks.getByName("api")
}
doFirst {
configuration {
classpath = moduleProjects.collect { project -> project.jar.outputs.files.getFiles() }.flatten()
classpath += files(moduleProjects.collect { it.sourceSets.main.compileClasspath })
moduleProjects.findAll {
it.pluginManager.hasPlugin("kotlin")
}.each { project ->
def kotlinDirs = project.sourceSets.main.kotlin.srcDirs.collect()
kotlinDirs -= project.sourceSets.main.java.srcDirs
kotlinDirs.each { dir ->
if (dir.exists()) {
sourceRoot {
path = dir.path
}
}
}
}
}
}
outputFormat = "html"
outputDirectory = "$buildDir/docs/kdoc"
configuration {
moduleName = "spring-framework"
externalDocumentationLink {
url = new URL("https://docs.spring.io/spring-framework/docs/$version/javadoc-api/")
packageListUrl = new File(buildDir, "docs/javadoc/package-list").toURI().toURL()
}
externalDocumentationLink {
url = new URL("https://projectreactor.io/docs/core/release/api/")
}
externalDocumentationLink {
url = new URL("https://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/")
}
/*
This link causes errors, removing to fix the build.
externalDocumentationLink {
url = new URL("https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/")
}
*/
externalDocumentationLink {
url = new URL("https://r2dbc.io/spec/0.8.3.RELEASE/api/")
}
moduleName.set("spring-framework")
outputDirectory.set(project.file("$buildDir/docs/kdoc"))
}
}
@@ -95,7 +139,7 @@ asciidoctorj {
icons: 'font',
idprefix: '',
idseparator: '-',
docinfo: 'shared,private-header', // https://docs.asciidoctor.org/asciidoctor/latest/docinfo/
docinfo: 'shared',
revnumber: project.version,
sectanchors: '',
sectnums: '',
@@ -119,6 +163,9 @@ asciidoctorj {
asciidoctor {
baseDirFollowsSourceDir()
configurations 'asciidoctorExt'
attributes([
noheader: '' // custom header in docinfo-header.html
])
sources {
include '*.adoc'
}
@@ -149,7 +196,7 @@ asciidoctorPdf {
/**
* Zip all docs (API and reference) into a single archive
*/
task docsZip(type: Zip, dependsOn: ['api', 'asciidoctor', 'asciidoctorPdf', 'dokkaHtmlMultiModule']) {
task docsZip(type: Zip, dependsOn: ['api', 'asciidoctor', 'asciidoctorPdf', 'dokka']) {
group = "Distribution"
description = "Builds -${archiveClassifier} archive containing api and reference " +
"for deployment at https://docs.spring.io/spring-framework/docs."
@@ -168,7 +215,7 @@ task docsZip(type: Zip, dependsOn: ['api', 'asciidoctor', 'asciidoctorPdf', 'dok
from ("$asciidoctorPdf.outputDir") {
into "reference/pdf"
}
from (dokkaHtmlMultiModule.outputDirectory) {
from (dokka) {
into "kdoc-api"
}
}
@@ -225,11 +272,11 @@ task distZip(type: Zip, dependsOn: [docsZip, schemaZip]) {
expand(copyright: new Date().format("yyyy"), version: project.version)
}
from(zipTree(docsZip.archiveFile)) {
from(zipTree(docsZip.archivePath)) {
into "${baseDir}/docs"
}
from(zipTree(schemaZip.archiveFile)) {
from(zipTree(schemaZip.archivePath)) {
into "${baseDir}/schema"
}
+42 -42
View File
@@ -1,7 +1,7 @@
import org.gradle.plugins.ide.eclipse.model.ProjectDependency
import org.gradle.plugins.ide.eclipse.model.SourceFolder
apply plugin: 'eclipse'
apply plugin: "eclipse"
eclipse.jdt {
sourceCompatibility = 1.8
@@ -18,45 +18,40 @@ eclipse.classpath.file.whenMerged { classpath ->
if (matcher) {
def projectName = matcher[0][1]
def path = "/${projectName}"
if (!classpath.entries.find { e -> e instanceof ProjectDependency && e.path == path }) {
def recursiveDependency = entry.path.matches('.+/' + projectName + '/build/([^/]+/)+(?:main|test)')
// Avoid recursive dependency on current project.
if (!recursiveDependency) {
classpath.entries.add(new ProjectDependency(path))
}
if(!classpath.entries.find { e -> e instanceof ProjectDependency && e.path == path }) {
def dependency = new ProjectDependency(path)
dependency.exported = true
classpath.entries.add(dependency)
}
classpath.entries.remove(entry)
}
}
// Remove any remaining direct depencencies on JARs in the build/libs folder
// except Spring's spring-cglib-repack and spring-objenesis-repack JARs.
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.defaultOutputDir = file(project.name+"/bin/eclipse")
eclipse.classpath.file.beforeMerged { classpath ->
classpath.entries.findAll{ it instanceof SourceFolder }.each {
if (it.output.startsWith('bin/')) {
if (it.output.startsWith("bin/")) {
it.output = null
}
}
}
eclipse.classpath.file.whenMerged {
entries.findAll{ it instanceof SourceFolder }.each {
it.output = 'bin/' + it.path.split('/')[1]
eclipse.classpath.file.whenMerged { classpath ->
classpath.entries.findAll{ it instanceof SourceFolder }.each {
it.output = "bin/" + it.path.split("/")[1]
}
}
// Ensure project dependencies come after 3rd-party libs (SPR-11836)
// https://jira.spring.io/browse/SPR-11836
eclipse.classpath.file.whenMerged {
entries.findAll { it instanceof ProjectDependency }.each {
eclipse.classpath.file.whenMerged { classpath ->
classpath.entries.findAll { it instanceof ProjectDependency }.each {
// delete from original position
entries.remove(it)
classpath.entries.remove(it)
// append to end of classpath
entries.add(it)
classpath.entries.add(it)
}
}
@@ -70,41 +65,46 @@ eclipse.classpath.file.whenMerged {
}
// Allow projects to be used as WTP modules
eclipse.project.natures 'org.eclipse.wst.common.project.facet.core.nature'
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')
"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 eclipseJdtSettings(type: Copy) {
from rootProject.file('src/eclipse/org.eclipse.jdt.core.prefs')
into project.file('.settings/')
outputs.upToDateWhen { false }
}
task eclipseBuildship {
dependsOn eclipseSettings, eclipseJdtSettings
}
task eclipseWstComponentSettings(type: Copy) {
from rootProject.files('src/eclipse/org.eclipse.wst.common.component')
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 cleanEclipseSettings(type: Delete) {
delete project.file('.settings/org.eclipse.jdt.core.prefs')
delete project.file('.settings/org.eclipse.jdt.ui.prefs')
delete project.file('.settings/org.eclipse.wst.common.component')
delete project.file('.settings/org.eclipse.wst.common.project.facet.core.xml')
task eclipseJdtPrepare(type: Copy) {
from rootProject.file("src/eclipse/org.eclipse.jdt.core.prefs")
into project.file(".settings/")
outputs.upToDateWhen { false }
}
tasks['eclipse'].dependsOn(eclipseSettings, eclipseJdtSettings, eclipseWstComponentSettings)
tasks['eclipseJdt'].dependsOn(eclipseJdtSettings)
tasks['cleanEclipse'].dependsOn(cleanEclipseSettings)
task cleanEclipseJdtUi(type: Delete) {
delete project.file(".settings/org.eclipse.jdt.core.prefs")
delete project.file(".settings/org.eclipse.jdt.ui.prefs")
delete project.file(".settings/org.eclipse.wst.common.component")
delete project.file(".settings/org.eclipse.wst.common.project.facet.core.xml")
}
task eclipseBuildship(type: Copy) {
from rootProject.files(
"src/eclipse/org.eclipse.jdt.ui.prefs",
"src/eclipse/org.eclipse.jdt.core.prefs")
into project.file('.settings/')
outputs.upToDateWhen { false }
}
tasks["eclipseJdt"].dependsOn(eclipseJdtPrepare)
tasks["cleanEclipse"].dependsOn(cleanEclipseJdtUi)
tasks["eclipse"].dependsOn(eclipseSettings, eclipseWstComponent)
+3 -7
View File
@@ -8,19 +8,15 @@ apply plugin: 'me.champeau.jmh'
apply from: "$rootDir/gradle/publications.gradle"
dependencies {
jmh 'org.openjdk.jmh:jmh-core:1.32'
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.32'
jmh 'net.sf.jopt-simple:jopt-simple'
jmh 'org.openjdk.jmh:jmh-core:1.28'
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.28'
jmh 'net.sf.jopt-simple:jopt-simple:4.6'
}
jmh {
duplicateClassesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.findByName("processJmhResources").configure {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
jmhJar {
// Uncomment the following for Shadow's Transformer support.
// mergeServiceFiles()
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+104 -153
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#!/usr/bin/env sh
#
# Copyright © 2015-2021 the original authors.
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -17,101 +17,67 @@
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
MAX_FD="maximum"
warn () {
echo "$*"
} >&2
}
die () {
echo
echo "$*"
echo
exit 1
} >&2
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -121,9 +87,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD=$JAVA_HOME/bin/java
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -132,7 +98,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
@@ -140,95 +106,80 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=$( cygpath --unix "$JAVACMD" )
JAVACMD=`cygpath --unix "$JAVACMD"`
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
+20 -20
View File
@@ -1,26 +1,26 @@
description = "Spring Integration Tests"
dependencies {
testImplementation(project(":spring-aop"))
testImplementation(project(":spring-beans"))
testImplementation(project(":spring-context"))
testImplementation(project(":spring-core"))
testImplementation(testFixtures(project(":spring-aop")))
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation(testFixtures(project(":spring-tx")))
testImplementation(project(":spring-expression"))
testImplementation(project(":spring-jdbc"))
testImplementation(project(":spring-orm"))
testImplementation(project(":spring-test"))
testImplementation(project(":spring-tx"))
testImplementation(project(":spring-web"))
testImplementation("javax.inject:javax.inject")
testImplementation("javax.resource:javax.resource-api")
testImplementation("javax.servlet:javax.servlet-api")
testImplementation("org.aspectj:aspectjweaver")
testImplementation("org.hsqldb:hsqldb")
testImplementation("org.hibernate:hibernate-core")
testCompile(project(":spring-aop"))
testCompile(project(":spring-beans"))
testCompile(project(":spring-context"))
testCompile(project(":spring-core"))
testCompile(testFixtures(project(":spring-aop")))
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-core")))
testCompile(testFixtures(project(":spring-tx")))
testCompile(project(":spring-expression"))
testCompile(project(":spring-jdbc"))
testCompile(project(":spring-orm"))
testCompile(project(":spring-test"))
testCompile(project(":spring-tx"))
testCompile(project(":spring-web"))
testCompile("javax.inject:javax.inject")
testCompile("javax.resource:javax.resource-api")
testCompile("javax.servlet:javax.servlet-api")
testCompile("org.aspectj:aspectjweaver")
testCompile("org.hsqldb:hsqldb")
testCompile("org.hibernate:hibernate-core")
}
normalization {
+4 -2
View File
@@ -1,7 +1,7 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven { url "https://repo.spring.io/plugins-release" }
maven { url 'https://repo.spring.io/plugins-release' }
}
}
@@ -17,6 +17,8 @@ include "spring-context"
include "spring-context-indexer"
include "spring-context-support"
include "spring-core"
include "kotlin-coroutines"
project(':kotlin-coroutines').projectDir = file('spring-core/kotlin-coroutines')
include "spring-expression"
include "spring-instrument"
include "spring-jcl"
@@ -49,7 +51,7 @@ settings.gradle.projectsLoaded {
buildScanPublished { scan ->
if (buildDir.exists()) {
new File(buildDir, "build-scan-uri.txt").text = "${scan.buildScanUri}\n"
}
}
}
}
}
+4 -5
View File
@@ -1,13 +1,12 @@
description = "Spring AOP"
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
optional("org.aspectj:aspectjweaver")
optional("org.apache.commons:commons-pool2")
optional("com.jamonapi:jamon")
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-core")))
testFixturesImplementation(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-core")))
testFixturesImplementation(testFixtures(project(":spring-core")))
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import javax.annotation.Nullable;
* terminology).
*
* <p>A runtime joinpoint is an <i>event</i> that occurs on a static
* joinpoint (i.e. a location in a program). For instance, an
* joinpoint (i.e. a location in a the program). For instance, an
* invocation is the runtime joinpoint on a method (static joinpoint).
* The static part of a given joinpoint can be generically retrieved
* using the {@link #getStaticPart()} method.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -103,11 +103,10 @@ public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFac
@Override
public void validate(Class<?> aspectClass) throws AopConfigException {
// If the parent has the annotation and isn't abstract it's an error
Class<?> superclass = aspectClass.getSuperclass();
if (superclass.getAnnotation(Aspect.class) != null &&
!Modifier.isAbstract(superclass.getModifiers())) {
if (aspectClass.getSuperclass().getAnnotation(Aspect.class) != null &&
!Modifier.isAbstract(aspectClass.getSuperclass().getModifiers())) {
throw new AopConfigException("[" + aspectClass.getName() + "] cannot extend concrete aspect [" +
superclass.getName() + "]");
aspectClass.getSuperclass().getName() + "]");
}
AjType<?> ajType = AjTypeSystem.getAjType(aspectClass);
@@ -521,8 +521,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
copy.copyFrom(this);
copy.targetSource = EmptyTargetSource.forClass(getTargetClass(), getTargetSource().isStatic());
copy.advisorChainFactory = this.advisorChainFactory;
copy.interfaces = new ArrayList<>(this.interfaces);
copy.advisors = new ArrayList<>(this.advisors);
copy.interfaces = this.interfaces;
copy.advisors = this.advisors;
return copy;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2018 the original author 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,8 +125,12 @@ public abstract class AbstractBeanFactoryBasedTargetSourceCreator
*/
protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) {
synchronized (this.internalBeanFactories) {
return this.internalBeanFactories.computeIfAbsent(beanName,
name -> buildInternalBeanFactory(this.beanFactory));
DefaultListableBeanFactory internalBeanFactory = this.internalBeanFactories.get(beanName);
if (internalBeanFactory == null) {
internalBeanFactory = buildInternalBeanFactory(this.beanFactory);
this.internalBeanFactories.put(beanName, internalBeanFactory);
}
return internalBeanFactory;
}
}
+8 -8
View File
@@ -11,7 +11,7 @@ sourceSets.test.java.srcDirs = files()
aspectj.version = dependencyManagement.managedVersions['org.aspectj:aspectjweaver']
dependencies {
api("org.aspectj:aspectjweaver")
compile("org.aspectj:aspectjweaver")
compileOnly("org.aspectj:aspectjrt")
optional(project(":spring-aop")) // for @Async support
optional(project(":spring-beans")) // for @Configurable support
@@ -21,13 +21,13 @@ dependencies {
optional(project(":spring-tx")) // for JPA, @Transactional support
optional("javax.cache:cache-api") // for JCache aspect
optional("javax.transaction:javax.transaction-api") // for @javax.transaction.Transactional support
testImplementation(project(":spring-core")) // for CodeStyleAspect
testImplementation(project(":spring-test"))
testImplementation(testFixtures(project(":spring-context")))
testImplementation(testFixtures(project(":spring-context-support")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation(testFixtures(project(":spring-tx")))
testImplementation("javax.mail:javax.mail-api")
testCompile(project(":spring-core")) // for CodeStyleAspect
testCompile(project(":spring-test"))
testCompile(testFixtures(project(":spring-context")))
testCompile(testFixtures(project(":spring-context-support")))
testCompile(testFixtures(project(":spring-core")))
testCompile(testFixtures(project(":spring-tx")))
testCompile("javax.mail:javax.mail-api")
testCompileOnly("org.aspectj:aspectjrt")
}
+3 -3
View File
@@ -4,14 +4,14 @@ apply plugin: "groovy"
apply plugin: "kotlin"
dependencies {
api(project(":spring-core"))
compile(project(":spring-core"))
optional("javax.inject:javax.inject")
optional("org.yaml:snakeyaml")
optional("org.codehaus.groovy:groovy-xml")
optional("org.jetbrains.kotlin:kotlin-reflect")
optional("org.jetbrains.kotlin:kotlin-stdlib")
testImplementation(testFixtures(project(":spring-core")))
testImplementation("javax.annotation:javax.annotation-api")
testCompile(testFixtures(project(":spring-core")))
testCompile("javax.annotation:javax.annotation-api")
testFixturesApi("org.junit.jupiter:junit-jupiter-api")
testFixturesImplementation("org.assertj:assertj-core")
}
@@ -87,10 +87,7 @@ public abstract class BeanUtils {
values.put(byte.class, (byte) 0);
values.put(short.class, (short) 0);
values.put(int.class, 0);
values.put(long.class, 0L);
values.put(float.class, 0F);
values.put(double.class, 0D);
values.put(char.class, '\0');
values.put(long.class, (long) 0);
DEFAULT_TYPE_VALUES = Collections.unmodifiableMap(values);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -138,7 +138,7 @@ final class GenericTypeAwarePropertyDescriptor extends PropertyDescriptor {
Set<Method> ambiguousCandidates = this.ambiguousWriteMethods;
if (ambiguousCandidates != null) {
this.ambiguousWriteMethods = null;
LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class).debug("Non-unique JavaBean property '" +
LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class).warn("Invalid JavaBean property '" +
getName() + "' being accessed! Ambiguous write methods found next to actually used [" +
this.writeMethod + "]: " + ambiguousCandidates);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -351,9 +351,7 @@ public class ConstructorArgumentValues {
* @return the ValueHolder for the argument, or {@code null} if none set
*/
@Nullable
public ValueHolder getArgumentValue(int index, @Nullable Class<?> requiredType,
@Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
public ValueHolder getArgumentValue(int index, @Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
Assert.isTrue(index >= 0, "Index must not be negative");
ValueHolder valueHolder = getIndexedArgumentValue(index, requiredType, requiredName);
if (valueHolder == null) {
@@ -246,15 +246,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
this.allowCircularReferences = allowCircularReferences;
}
/**
* Return whether to allow circular references between beans.
* @since 5.3.10
* @see #setAllowCircularReferences
*/
public boolean isAllowCircularReferences() {
return this.allowCircularReferences;
}
/**
* Set whether to allow the raw injection of a bean instance into some other
* bean's property, despite the injected bean eventually getting wrapped
@@ -273,15 +264,6 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
}
/**
* Return whether to allow the raw injection of a bean instance.
* @since 5.3.10
* @see #setAllowRawInjectionDespiteWrapping
*/
public boolean isAllowRawInjectionDespiteWrapping() {
return this.allowRawInjectionDespiteWrapping;
}
/**
* Ignore the given dependency type for autowiring:
* for example, String. Default is none.
@@ -49,7 +49,6 @@ import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.SoftAssertions.assertSoftly;
/**
* Unit tests for {@link BeanUtils}.
@@ -86,43 +85,19 @@ class BeanUtilsTests {
}
@Test // gh-22531
void instantiateClassWithFewerArgsThanParameters() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor();
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() ->
BeanUtils.instantiateClass(constructor, null, null, "foo"));
void instantiateClassWithOptionalPrimitiveType() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class);
BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(ctor, null, null, "foo");
assertThat(bean.getCounter()).isEqualTo(0);
assertThat(bean.isFlag()).isEqualTo(false);
assertThat(bean.getValue()).isEqualTo("foo");
}
@Test // gh-22531
void instantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor();
Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class);
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() ->
BeanUtils.instantiateClass(constructor, null, null, null, null, null, null, null, null, "foo", null));
}
@Test // gh-22531, gh-27390
void instantiateClassWithOptionalPrimitiveTypes() throws NoSuchMethodException {
Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor();
BeanWithPrimitiveTypes bean = BeanUtils.instantiateClass(constructor, null, null, null, null, null, null, null, null, "foo");
assertSoftly(softly -> {
softly.assertThat(bean.isFlag()).isFalse();
softly.assertThat(bean.getByteCount()).isEqualTo((byte) 0);
softly.assertThat(bean.getShortCount()).isEqualTo((short) 0);
softly.assertThat(bean.getIntCount()).isEqualTo(0);
softly.assertThat(bean.getLongCount()).isEqualTo(0L);
softly.assertThat(bean.getFloatCount()).isEqualTo(0F);
softly.assertThat(bean.getDoubleCount()).isEqualTo(0D);
softly.assertThat(bean.getCharacter()).isEqualTo('\0');
softly.assertThat(bean.getText()).isEqualTo("foo");
});
}
private Constructor<BeanWithPrimitiveTypes> getBeanWithPrimitiveTypesConstructor() throws NoSuchMethodException {
return BeanWithPrimitiveTypes.class.getConstructor(boolean.class, byte.class, short.class, int.class,
long.class, float.class, double.class, char.class, String.class);
BeanUtils.instantiateClass(ctor, null, null, "foo", null));
}
@Test
@@ -653,68 +628,30 @@ class BeanUtilsTests {
private static class BeanWithPrimitiveTypes {
private boolean flag;
private byte byteCount;
private short shortCount;
private int intCount;
private long longCount;
private float floatCount;
private double doubleCount;
private char character;
private String text;
private int counter;
private boolean flag;
private String value;
@SuppressWarnings("unused")
public BeanWithPrimitiveTypes(boolean flag, byte byteCount, short shortCount, int intCount, long longCount,
float floatCount, double doubleCount, char character, String text) {
public BeanWithPrimitiveTypes(int counter, boolean flag, String value) {
this.counter = counter;
this.flag = flag;
this.byteCount = byteCount;
this.shortCount = shortCount;
this.intCount = intCount;
this.longCount = longCount;
this.floatCount = floatCount;
this.doubleCount = doubleCount;
this.character = character;
this.text = text;
this.value = value;
}
public int getCounter() {
return counter;
}
public boolean isFlag() {
return flag;
}
public byte getByteCount() {
return byteCount;
public String getValue() {
return value;
}
public short getShortCount() {
return shortCount;
}
public int getIntCount() {
return intCount;
}
public long getLongCount() {
return longCount;
}
public float getFloatCount() {
return floatCount;
}
public double getDoubleCount() {
return doubleCount;
}
public char getCharacter() {
return character;
}
public String getText() {
return text;
}
}
private static class PrivateBeanWithPrivateConstructor {
@@ -38,7 +38,7 @@ public class BeanWrapperAutoGrowingTests {
@BeforeEach
public void setup() {
public void setUp() {
wrapper.setAutoGrowNestedPaths(true);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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.beans;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -45,10 +46,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Chris Beams
* @since 18.01.2006
*/
class BeanWrapperGenericsTests {
public class BeanWrapperGenericsTests {
@Test
void testGenericSet() {
public void testGenericSet() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set<String> input = new HashSet<>();
@@ -60,7 +61,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericLowerBoundedSet() {
public void testGenericLowerBoundedSet() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, true));
@@ -73,7 +74,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericSetWithConversionFailure() {
public void testGenericSetWithConversionFailure() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set<TestBean> input = new HashSet<>();
@@ -84,7 +85,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericList() throws Exception {
public void testGenericList() throws MalformedURLException {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
List<String> input = new ArrayList<>();
@@ -96,7 +97,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericListElement() throws Exception {
public void testGenericListElement() throws MalformedURLException {
GenericBean<?> gb = new GenericBean<>();
gb.setResourceList(new ArrayList<>());
BeanWrapper bw = new BeanWrapperImpl(gb);
@@ -105,29 +106,29 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericMap() {
public void testGenericMap() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map<String, String> input = new HashMap<>();
input.put("4", "5");
input.put("6", "7");
bw.setPropertyValue("shortMap", input);
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericMapElement() {
public void testGenericMapElement() {
GenericBean<?> gb = new GenericBean<>();
gb.setShortMap(new HashMap<>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("shortMap[4]", "5");
assertThat(bw.getPropertyValue("shortMap[4]")).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
}
@Test
void testGenericMapWithKeyType() {
public void testGenericMapWithKeyType() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map<String, String> input = new HashMap<>();
@@ -139,17 +140,17 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericMapElementWithKeyType() {
public void testGenericMapElementWithKeyType() {
GenericBean<?> gb = new GenericBean<>();
gb.setLongMap(new HashMap<Long, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("longMap[4]", "5");
assertThat(gb.getLongMap().get(Long.valueOf("4"))).isEqualTo("5");
assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5");
assertThat(bw.getPropertyValue("longMap[4]")).isEqualTo("5");
}
@Test
void testGenericMapWithCollectionValue() {
public void testGenericMapWithCollectionValue() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
@@ -161,12 +162,14 @@ class BeanWrapperGenericsTests {
value2.add(Boolean.TRUE);
input.put("2", value2);
bw.setPropertyValue("collectionMap", input);
assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue();
assertThat(gb.getCollectionMap().get(2) instanceof ArrayList).isTrue();
boolean condition1 = gb.getCollectionMap().get(1) instanceof HashSet;
assertThat(condition1).isTrue();
boolean condition = gb.getCollectionMap().get(2) instanceof ArrayList;
assertThat(condition).isTrue();
}
@Test
void testGenericMapElementWithCollectionValue() {
public void testGenericMapElementWithCollectionValue() {
GenericBean<?> gb = new GenericBean<>();
gb.setCollectionMap(new HashMap<>());
BeanWrapper bw = new BeanWrapperImpl(gb);
@@ -174,23 +177,24 @@ class BeanWrapperGenericsTests {
HashSet<Integer> value1 = new HashSet<>();
value1.add(1);
bw.setPropertyValue("collectionMap[1]", value1);
assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue();
boolean condition = gb.getCollectionMap().get(1) instanceof HashSet;
assertThat(condition).isTrue();
}
@Test
void testGenericMapFromProperties() {
public void testGenericMapFromProperties() {
GenericBean<?> gb = new GenericBean<>();
BeanWrapper bw = new BeanWrapperImpl(gb);
Properties input = new Properties();
input.setProperty("4", "5");
input.setProperty("6", "7");
bw.setPropertyValue("shortMap", input);
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericListOfLists() {
public void testGenericListOfLists() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
List<List<Integer>> list = new ArrayList<>();
list.add(new ArrayList<>());
@@ -202,7 +206,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericListOfListsWithElementConversion() {
public void testGenericListOfListsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
List<List<Integer>> list = new ArrayList<>();
list.add(new ArrayList<>());
@@ -214,7 +218,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericListOfArrays() {
public void testGenericListOfArrays() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {"str1", "str2"});
@@ -226,7 +230,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericListOfArraysWithElementConversion() {
public void testGenericListOfArraysWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {"str1", "str2"});
@@ -239,55 +243,55 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericListOfMaps() {
public void testGenericListOfMaps() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
List<Map<Integer, Long>> list = new ArrayList<>();
list.add(new HashMap<>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", 5L);
assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(5L);
assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(Long.valueOf(5));
bw.setPropertyValue("listOfMaps[0][10]", new Long(5));
assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5));
assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5));
}
@Test
void testGenericListOfMapsWithElementConversion() {
public void testGenericListOfMapsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
List<Map<Integer, Long>> list = new ArrayList<>();
list.add(new HashMap<>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", "5");
assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(5L);
assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(Long.valueOf(5));
assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5));
assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5));
}
@Test
void testGenericMapOfMaps() {
public void testGenericMapOfMaps() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
Map<String, Map<Integer, Long>> map = new HashMap<>();
map.put("mykey", new HashMap<>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", 5L);
assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(5L);
assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(Long.valueOf(5));
bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5));
assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5));
assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5));
}
@Test
void testGenericMapOfMapsWithElementConversion() {
public void testGenericMapOfMapsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
Map<String, Map<Integer, Long>> map = new HashMap<>();
map.put("mykey", new HashMap<>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", "5");
assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(Long.valueOf(5));
assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(Long.valueOf(5));
assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5));
assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5));
}
@Test
void testGenericMapOfLists() {
public void testGenericMapOfLists() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, new ArrayList<>());
@@ -299,7 +303,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericMapOfListsWithElementConversion() {
public void testGenericMapOfListsWithElementConversion() throws MalformedURLException {
GenericBean<String> gb = new GenericBean<>();
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, new ArrayList<>());
@@ -311,7 +315,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericTypeNestingMapOfInteger() {
public void testGenericTypeNestingMapOfInteger() throws Exception {
Map<String, String> map = new HashMap<>();
map.put("testKey", "100");
@@ -320,13 +324,14 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfInteger", map);
Object obj = gb.getMapOfInteger().get("testKey");
assertThat(obj instanceof Integer).isTrue();
boolean condition = obj instanceof Integer;
assertThat(condition).isTrue();
}
@Test
void testGenericTypeNestingMapOfListOfInteger() {
public void testGenericTypeNestingMapOfListOfInteger() throws Exception {
Map<String, List<String>> map = new HashMap<>();
List<String> list = Arrays.asList("1", "2", "3");
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", list);
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
@@ -334,12 +339,13 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfListOfInteger", map);
Object obj = gb.getMapOfListOfInteger().get("testKey").get(0);
assertThat(obj instanceof Integer).isTrue();
boolean condition = obj instanceof Integer;
assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(1);
}
@Test
void testGenericTypeNestingListOfMapOfInteger() {
public void testGenericTypeNestingListOfMapOfInteger() throws Exception {
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("testKey", "5");
@@ -350,14 +356,15 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("listOfMapOfInteger", list);
Object obj = gb.getListOfMapOfInteger().get(0).get("testKey");
assertThat(obj instanceof Integer).isTrue();
boolean condition = obj instanceof Integer;
assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(5);
}
@Test
void testGenericTypeNestingMapOfListOfListOfInteger() {
public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception {
Map<String, List<List<String>>> map = new HashMap<>();
List<String> list = Arrays.asList("1", "2", "3");
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", Collections.singletonList(list));
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
@@ -365,12 +372,13 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("mapOfListOfListOfInteger", map);
Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
assertThat(obj instanceof Integer).isTrue();
boolean condition = obj instanceof Integer;
assertThat(condition).isTrue();
assertThat(((Integer) obj).intValue()).isEqualTo(1);
}
@Test
void testComplexGenericMap() {
public void testComplexGenericMap() {
Map<List<String>, List<String>> inputMap = new HashMap<>();
List<String> inputKey = new ArrayList<>();
inputKey.add("1");
@@ -383,11 +391,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("genericMap", inputMap);
assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(1);
assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testComplexGenericMapWithCollectionConversion() {
public void testComplexGenericMapWithCollectionConversion() {
Map<Set<String>, Set<String>> inputMap = new HashMap<>();
Set<String> inputKey = new HashSet<>();
inputKey.add("1");
@@ -400,11 +408,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("genericMap", inputMap);
assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(1);
assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testComplexGenericIndexedMapEntry() {
public void testComplexGenericIndexedMapEntry() {
List<String> inputValue = new ArrayList<>();
inputValue.add("10");
@@ -413,11 +421,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(1);
assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testComplexGenericIndexedMapEntryWithCollectionConversion() {
public void testComplexGenericIndexedMapEntryWithCollectionConversion() {
Set<String> inputValue = new HashSet<>();
inputValue.add("10");
@@ -426,11 +434,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(1);
assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testComplexDerivedIndexedMapEntry() {
public void testComplexDerivedIndexedMapEntry() {
List<String> inputValue = new ArrayList<>();
inputValue.add("10");
@@ -439,11 +447,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(1);
assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testComplexDerivedIndexedMapEntryWithCollectionConversion() {
public void testComplexDerivedIndexedMapEntryWithCollectionConversion() {
Set<String> inputValue = new HashSet<>();
inputValue.add("10");
@@ -452,11 +460,11 @@ class BeanWrapperGenericsTests {
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(1);
assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10));
assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10));
}
@Test
void testGenericallyTypedIntegerBean() {
public void testGenericallyTypedIntegerBean() throws Exception {
GenericIntegerBean gb = new GenericIntegerBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10");
@@ -467,7 +475,7 @@ class BeanWrapperGenericsTests {
}
@Test
void testGenericallyTypedSetOfIntegerBean() {
public void testGenericallyTypedSetOfIntegerBean() throws Exception {
GenericSetOfIntegerBean gb = new GenericSetOfIntegerBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("genericProperty", "10");
@@ -478,23 +486,23 @@ class BeanWrapperGenericsTests {
}
@Test
void testSettingGenericPropertyWithReadOnlyInterface() {
public void testSettingGenericPropertyWithReadOnlyInterface() {
Bar bar = new Bar();
BeanWrapper bw = new BeanWrapperImpl(bar);
bw.setPropertyValue("version", "10");
assertThat(bar.getVersion()).isEqualTo(Double.valueOf(10.0));
assertThat(bar.getVersion()).isEqualTo(new Double(10.0));
}
@Test
void testSettingLongPropertyWithGenericInterface() {
public void testSettingLongPropertyWithGenericInterface() {
Promotion bean = new Promotion();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("id", "10");
assertThat(bean.getId()).isEqualTo(Long.valueOf(10));
assertThat(bean.getId()).isEqualTo(new Long(10));
}
@Test
void testUntypedPropertyWithMapAtRuntime() {
public void testUntypedPropertyWithMapAtRuntime() {
class Holder<D> {
private final D data;
public Holder(D data) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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 org.springframework.beans.testfixture.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* Specific {@link BeanWrapperImpl} tests.
@@ -38,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThatNoException;
* @author Chris Beams
* @author Dave Syer
*/
class BeanWrapperTests extends AbstractPropertyAccessorTests {
public class BeanWrapperTests extends AbstractPropertyAccessorTests {
@Override
protected BeanWrapperImpl createAccessor(Object target) {
@@ -47,7 +46,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
@Test
void setterDoesNotCallGetter() {
public void setterDoesNotCallGetter() {
GetterBean target = new GetterBean();
BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("name", "tom");
@@ -56,7 +55,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void getterSilentlyFailWithOldValueExtraction() {
public void getterSilentlyFailWithOldValueExtraction() {
GetterBean target = new GetterBean();
BeanWrapper accessor = createAccessor(target);
accessor.setExtractOldValueForEditor(true); // This will call the getter
@@ -66,7 +65,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void aliasedSetterThroughDefaultMethod() {
public void aliasedSetterThroughDefaultMethod() {
GetterBean target = new GetterBean();
BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("aliasedName", "tom");
@@ -75,7 +74,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void setValidAndInvalidPropertyValuesShouldContainExceptionDetails() {
public void setValidAndInvalidPropertyValuesShouldContainExceptionDetails() {
TestBean target = new TestBean();
String newName = "tony";
String invalidTouchy = ".valid";
@@ -92,12 +91,12 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
.getNewValue()).isEqualTo(invalidTouchy);
});
// Test validly set property matches
assertThat(target.getName()).as("Valid set property must stick").isEqualTo(newName);
assertThat(target.getAge()).as("Invalid set property must retain old value").isEqualTo(0);
assertThat(target.getName().equals(newName)).as("Valid set property must stick").isTrue();
assertThat(target.getAge() == 0).as("Invalid set property must retain old value").isTrue();
}
@Test
void checkNotWritablePropertyHoldPossibleMatches() {
public void checkNotWritablePropertyHoldPossibleMatches() {
TestBean target = new TestBean();
BeanWrapper accessor = createAccessor(target);
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
@@ -106,15 +105,15 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test // Can't be shared; there is no such thing as a read-only field
void setReadOnlyMapProperty() {
public void setReadOnlyMapProperty() {
TypedReadOnlyMap map = new TypedReadOnlyMap(Collections.singletonMap("key", new TestBean()));
TypedReadOnlyMapClient target = new TypedReadOnlyMapClient();
BeanWrapper accessor = createAccessor(target);
assertThatNoException().isThrownBy(() -> accessor.setPropertyValue("map", map));
accessor.setPropertyValue("map", map);
}
@Test
void notWritablePropertyExceptionContainsAlternativeMatch() {
public void notWritablePropertyExceptionContainsAlternativeMatch() {
IntelliBean target = new IntelliBean();
BeanWrapper bw = createAccessor(target);
try {
@@ -122,12 +121,12 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
catch (NotWritablePropertyException ex) {
assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull();
assertThat(ex.getPossibleMatches()).as("Invalid amount of alternatives").hasSize(1);
assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(1);
}
}
@Test
void notWritablePropertyExceptionContainsAlternativeMatches() {
public void notWritablePropertyExceptionContainsAlternativeMatches() {
IntelliBean target = new IntelliBean();
BeanWrapper bw = createAccessor(target);
try {
@@ -135,23 +134,23 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
catch (NotWritablePropertyException ex) {
assertThat(ex.getPossibleMatches()).as("Possible matches not determined").isNotNull();
assertThat(ex.getPossibleMatches()).as("Invalid amount of alternatives").hasSize(3);
assertThat(ex.getPossibleMatches().length).as("Invalid amount of alternatives").isEqualTo(3);
}
}
@Override
@Test // Can't be shared: no type mismatch with a field
void setPropertyTypeMismatch() {
public void setPropertyTypeMismatch() {
PropertyTypeMismatch target = new PropertyTypeMismatch();
BeanWrapper accessor = createAccessor(target);
accessor.setPropertyValue("object", "a String");
assertThat(target.value).isEqualTo("a String");
assertThat(target.getObject()).isEqualTo(8);
assertThat(target.getObject() == 8).isTrue();
assertThat(accessor.getPropertyValue("object")).isEqualTo(8);
}
@Test
void propertyDescriptors() {
public void propertyDescriptors() {
TestBean target = new TestBean();
target.setSpouse(new TestBean());
BeanWrapper accessor = createAccessor(target);
@@ -167,7 +166,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
@Test
@SuppressWarnings("unchecked")
void getPropertyWithOptional() {
public void getPropertyWithOptional() {
GetterWithOptional target = new GetterWithOptional();
TestBean tb = new TestBean("x");
BeanWrapper accessor = createAccessor(target);
@@ -190,7 +189,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void getPropertyWithOptionalAndAutoGrow() {
public void getPropertyWithOptionalAndAutoGrow() {
GetterWithOptional target = new GetterWithOptional();
BeanWrapper accessor = createAccessor(target);
accessor.setAutoGrowNestedPaths(true);
@@ -202,7 +201,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void incompletelyQuotedKeyLeadsToPropertyException() {
public void incompletelyQuotedKeyLeadsToPropertyException() {
TestBean target = new TestBean();
BeanWrapper accessor = createAccessor(target);
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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.assertj.core.api.Assertions.assertThat;
* @author Chris Beams
* @author Stephane Nicoll
*/
class DirectFieldAccessorTests extends AbstractPropertyAccessorTests {
public class DirectFieldAccessorTests extends AbstractPropertyAccessorTests {
@Override
protected DirectFieldAccessor createAccessor(Object target) {
@@ -38,7 +38,7 @@ class DirectFieldAccessorTests extends AbstractPropertyAccessorTests {
@Test
void withShadowedField() {
public void withShadowedField() {
final StringBuilder sb = new StringBuilder();
TestBean target = new TestBean() {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -182,9 +182,9 @@ class DefaultListableBeanFactoryTests {
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -216,9 +216,9 @@ class DefaultListableBeanFactoryTests {
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -249,9 +249,9 @@ class DefaultListableBeanFactoryTests {
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertThat(beanNames.length).isEqualTo(0);
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -283,7 +283,7 @@ class DefaultListableBeanFactoryTests {
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(lbf.containsSingleton("x1")).isTrue();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -337,7 +337,7 @@ class DefaultListableBeanFactoryTests {
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -349,7 +349,7 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue();
assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse();
assertThat(lbf.getType("x1")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x1")).isNull();
assertThat(lbf.getType("&x1")).isEqualTo(null);
assertThat(TestBeanFactory.initialized).isFalse();
}
@@ -362,7 +362,7 @@ class DefaultListableBeanFactoryTests {
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -374,7 +374,7 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue();
assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse();
assertThat(lbf.getType("x1")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x1")).isNull();
assertThat(lbf.getType("&x1")).isEqualTo(null);
assertThat(TestBeanFactory.initialized).isFalse();
}
@@ -389,7 +389,7 @@ class DefaultListableBeanFactoryTests {
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -401,7 +401,7 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue();
assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse();
assertThat(lbf.getType("x1")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x1")).isNull();
assertThat(lbf.getType("&x1")).isEqualTo(null);
assertThat(TestBeanFactory.initialized).isFalse();
}
@@ -417,7 +417,7 @@ class DefaultListableBeanFactoryTests {
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -450,7 +450,7 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("x2", Object.class)).isTrue();
assertThat(lbf.isTypeMatch("&x2", Object.class)).isFalse();
assertThat(lbf.getType("x2")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x2")).isNull();
assertThat(lbf.getType("&x2")).isEqualTo(null);
assertThat(lbf.getAliases("x1").length).isEqualTo(1);
assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2");
assertThat(lbf.getAliases("&x1").length).isEqualTo(1);
@@ -3030,7 +3030,7 @@ class DefaultListableBeanFactoryTests {
public Object convertIfNecessary(Object value, @Nullable Class requiredType) {
if (value instanceof String && Float.class.isAssignableFrom(requiredType)) {
try {
return this.numberFormat.parse((String) value).floatValue();
return new Float(this.numberFormat.parse((String) value).floatValue());
}
catch (ParseException ex) {
throw new TypeMismatchException(value, requiredType, ex);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 static org.springframework.core.testfixture.TestGroup.LONG_RUNNING;
* @author Sam Brannen
* @since 20.01.2006
*/
class BeanFactoryGenericsTests {
public class BeanFactoryGenericsTests {
@Test
void testGenericSetProperty() {
public void testGenericSetProperty() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -84,7 +84,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericListProperty() throws Exception {
public void testGenericListProperty() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -101,7 +101,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericListPropertyWithAutowiring() throws Exception {
public void testGenericListPropertyWithAutowiring() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));
@@ -116,7 +116,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericListPropertyWithInvalidElementType() {
public void testGenericListPropertyWithInvalidElementType() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericIntegerBean.class);
@@ -134,7 +134,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericListPropertyWithOptionalAutowiring() {
public void testGenericListPropertyWithOptionalAutowiring() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -146,7 +146,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericMapProperty() {
public void testGenericMapProperty() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -158,12 +158,12 @@ class BeanFactoryGenericsTests {
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericListOfArraysProperty() {
public void testGenericListOfArraysProperty() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -171,14 +171,14 @@ class BeanFactoryGenericsTests {
assertThat(gb.getListOfArrays().size()).isEqualTo(1);
String[] array = gb.getListOfArrays().get(0);
assertThat(array).hasSize(2);
assertThat(array.length).isEqualTo(2);
assertThat(array[0]).isEqualTo("value1");
assertThat(array[1]).isEqualTo("value2");
}
@Test
void testGenericSetConstructor() {
public void testGenericSetConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -195,7 +195,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetConstructorWithAutowiring() {
public void testGenericSetConstructorWithAutowiring() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("integer1", 4);
bf.registerSingleton("integer2", 5);
@@ -210,7 +210,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetConstructorWithOptionalAutowiring() {
public void testGenericSetConstructorWithOptionalAutowiring() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -222,7 +222,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetListConstructor() throws Exception {
public void testGenericSetListConstructor() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -245,7 +245,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetListConstructorWithAutowiring() throws Exception {
public void testGenericSetListConstructorWithAutowiring() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("integer1", 4);
bf.registerSingleton("integer2", 5);
@@ -264,7 +264,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetListConstructorWithOptionalAutowiring() throws Exception {
public void testGenericSetListConstructorWithOptionalAutowiring() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));
@@ -279,7 +279,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetMapConstructor() {
public void testGenericSetMapConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -297,12 +297,12 @@ class BeanFactoryGenericsTests {
assertThat(gb.getIntegerSet().contains(4)).isTrue();
assertThat(gb.getIntegerSet().contains(5)).isTrue();
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericMapResourceConstructor() throws Exception {
public void testGenericMapResourceConstructor() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -315,13 +315,13 @@ class BeanFactoryGenericsTests {
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080"));
}
@Test
void testGenericMapMapConstructor() {
public void testGenericMapMapConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -338,16 +338,16 @@ class BeanFactoryGenericsTests {
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap());
assertThat(gb.getPlainMap()).hasSize(2);
assertThat(gb.getPlainMap().size()).isEqualTo(2);
assertThat(gb.getPlainMap().get("1")).isEqualTo("0");
assertThat(gb.getPlainMap().get("2")).isEqualTo("3");
assertThat(gb.getShortMap().size()).isEqualTo(2);
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericMapMapConstructorWithSameRefAndConversion() {
public void testGenericMapMapConstructorWithSameRefAndConversion() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -361,22 +361,22 @@ class BeanFactoryGenericsTests {
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap());
assertThat(gb.getPlainMap()).hasSize(2);
assertThat(gb.getPlainMap().size()).isEqualTo(2);
assertThat(gb.getPlainMap().get("1")).isEqualTo("0");
assertThat(gb.getPlainMap().get("2")).isEqualTo("3");
assertThat(gb.getShortMap().size()).isEqualTo(2);
assertThat(gb.getShortMap().get(Short.valueOf("1"))).isEqualTo(0);
assertThat(gb.getShortMap().get(Short.valueOf("2"))).isEqualTo(3);
assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(0);
assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(3);
}
@Test
void testGenericMapMapConstructorWithSameRefAndNoConversion() {
public void testGenericMapMapConstructorWithSameRefAndNoConversion() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<Short, Integer> input = new HashMap<>();
input.put((short) 1, 0);
input.put((short) 2, 3);
input.put(new Short((short) 1), 0);
input.put(new Short((short) 2), 3);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
@@ -384,13 +384,13 @@ class BeanFactoryGenericsTests {
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap()).isSameAs(gb.getPlainMap());
assertThat(gb.getShortMap()).hasSize(2);
assertThat(gb.getShortMap().get(Short.valueOf("1"))).isEqualTo(0);
assertThat(gb.getShortMap().get(Short.valueOf("2"))).isEqualTo(3);
assertThat(gb.getShortMap().size()).isEqualTo(2);
assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(0);
assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(3);
}
@Test
void testGenericMapWithKeyTypeConstructor() {
public void testGenericMapWithKeyTypeConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
@@ -407,7 +407,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericMapWithCollectionValueConstructor() {
public void testGenericMapWithCollectionValueConstructor() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
@@ -438,7 +438,7 @@ class BeanFactoryGenericsTests {
@Test
void testGenericSetFactoryMethod() {
public void testGenericSetFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -456,7 +456,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetListFactoryMethod() throws Exception {
public void testGenericSetListFactoryMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -480,7 +480,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetMapFactoryMethod() {
public void testGenericSetMapFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -499,12 +499,12 @@ class BeanFactoryGenericsTests {
assertThat(gb.getIntegerSet().contains(4)).isTrue();
assertThat(gb.getIntegerSet().contains(5)).isTrue();
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericMapResourceFactoryMethod() throws Exception {
public void testGenericMapResourceFactoryMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -518,13 +518,13 @@ class BeanFactoryGenericsTests {
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080"));
}
@Test
void testGenericMapMapFactoryMethod() {
public void testGenericMapMapFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -543,12 +543,12 @@ class BeanFactoryGenericsTests {
assertThat(gb.getPlainMap().get("1")).isEqualTo("0");
assertThat(gb.getPlainMap().get("2")).isEqualTo("3");
assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7);
assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5);
assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7);
}
@Test
void testGenericMapWithKeyTypeFactoryMethod() {
public void testGenericMapWithKeyTypeFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
@@ -561,12 +561,12 @@ class BeanFactoryGenericsTests {
bf.registerBeanDefinition("genericBean", rbd);
GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");
assertThat(gb.getLongMap().get(Long.valueOf("4"))).isEqualTo("5");
assertThat(gb.getLongMap().get(Long.valueOf("6"))).isEqualTo("7");
assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5");
assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7");
}
@Test
void testGenericMapWithCollectionValueFactoryMethod() {
public void testGenericMapWithCollectionValueFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
@Override
@@ -597,7 +597,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericListBean() throws Exception {
public void testGenericListBean() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -607,7 +607,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericSetBean() throws Exception {
public void testGenericSetBean() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -617,18 +617,18 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericMapBean() throws Exception {
public void testGenericMapBean() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
Map<?, ?> map = (Map<?, ?>) bf.getBean("map");
assertThat(map).hasSize(1);
assertThat(map.size()).isEqualTo(1);
assertThat(map.keySet().iterator().next()).isEqualTo(10);
assertThat(map.values().iterator().next()).isEqualTo(new URL("http://localhost:8080"));
}
@Test
void testGenericallyTypedIntegerBean() {
public void testGenericallyTypedIntegerBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -639,7 +639,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericallyTypedSetOfIntegerBean() {
public void testGenericallyTypedSetOfIntegerBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -651,7 +651,7 @@ class BeanFactoryGenericsTests {
@Test
@EnabledForTestGroups(LONG_RUNNING)
void testSetBean() throws Exception {
public void testSetBean() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("genericBeanTests.xml", getClass()));
@@ -671,7 +671,7 @@ class BeanFactoryGenericsTests {
* <p>See SPR-9493
*/
@Test
void parameterizedStaticFactoryMethod() {
public void parameterizedStaticFactoryMethod() {
RootBeanDefinition rbd = new RootBeanDefinition(Mockito.class);
rbd.setFactoryMethodName("mock");
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
@@ -682,7 +682,7 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
/**
@@ -697,7 +697,7 @@ class BeanFactoryGenericsTests {
* <p>See SPR-10411
*/
@Test
void parameterizedInstanceFactoryMethod() {
public void parameterizedInstanceFactoryMethod() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
@@ -714,11 +714,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
@Test
void parameterizedInstanceFactoryMethodWithNonResolvedClassName() {
public void parameterizedInstanceFactoryMethodWithNonResolvedClassName() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
@@ -735,11 +735,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
@Test
void parameterizedInstanceFactoryMethodWithWrappedClassName() {
public void parameterizedInstanceFactoryMethodWithWrappedClassName() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition();
@@ -754,11 +754,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
@Test
void parameterizedInstanceFactoryMethodWithInvalidClassName() {
public void parameterizedInstanceFactoryMethodWithInvalidClassName() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
@@ -775,11 +775,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isNull();
assertThat(bf.getType("mock")).isNull();
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(0);
assertThat(beans.size()).isEqualTo(0);
}
@Test
void parameterizedInstanceFactoryMethodWithIndexedArgument() {
public void parameterizedInstanceFactoryMethodWithIndexedArgument() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class);
@@ -796,11 +796,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
@Test // SPR-16720
void parameterizedInstanceFactoryMethodWithTempClassLoader() {
public void parameterizedInstanceFactoryMethodWithTempClassLoader() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setTempClassLoader(new OverridingClassLoader(getClass().getClassLoader()));
@@ -818,11 +818,11 @@ class BeanFactoryGenericsTests {
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
assertThat(bf.getType("mock")).isEqualTo(Runnable.class);
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
assertThat(beans).hasSize(1);
assertThat(beans.size()).isEqualTo(1);
}
@Test
void testGenericMatchingWithBeanNameDifferentiation() {
public void testGenericMatchingWithBeanNameDifferentiation() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver());
@@ -838,15 +838,15 @@ class BeanFactoryGenericsTests {
String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class));
String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class));
String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class));
assertThat(numberStoreNames).hasSize(2);
assertThat(numberStoreNames.length).isEqualTo(2);
assertThat(numberStoreNames[0]).isEqualTo("doubleStore");
assertThat(numberStoreNames[1]).isEqualTo("floatStore");
assertThat(doubleStoreNames).hasSize(0);
assertThat(floatStoreNames).hasSize(0);
assertThat(doubleStoreNames.length).isEqualTo(0);
assertThat(floatStoreNames.length).isEqualTo(0);
}
@Test
void testGenericMatchingWithFullTypeDifferentiation() {
public void testGenericMatchingWithFullTypeDifferentiation() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver());
@@ -867,12 +867,12 @@ class BeanFactoryGenericsTests {
String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class));
String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class));
String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class));
assertThat(numberStoreNames).hasSize(2);
assertThat(numberStoreNames.length).isEqualTo(2);
assertThat(numberStoreNames[0]).isEqualTo("store1");
assertThat(numberStoreNames[1]).isEqualTo("store2");
assertThat(doubleStoreNames).hasSize(1);
assertThat(doubleStoreNames.length).isEqualTo(1);
assertThat(doubleStoreNames[0]).isEqualTo("store1");
assertThat(floatStoreNames).hasSize(1);
assertThat(floatStoreNames.length).isEqualTo(1);
assertThat(floatStoreNames[0]).isEqualTo("store2");
ObjectProvider<NumberStore<?>> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class));
@@ -938,7 +938,7 @@ class BeanFactoryGenericsTests {
}
@Test
void testGenericMatchingWithUnresolvedOrderedStream() {
public void testGenericMatchingWithUnresolvedOrderedStream() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,18 +26,18 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Rick Evans
*/
class ClassNameBeanWiringInfoResolverTests {
public class ClassNameBeanWiringInfoResolverTests {
@Test
void resolveWiringInfoWithNullBeanInstance() throws Exception {
public void resolveWiringInfoWithNullBeanInstance() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() ->
new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null));
}
@Test
void resolveWiringInfo() {
public void resolveWiringInfo() {
ClassNameBeanWiringInfoResolver resolver = new ClassNameBeanWiringInfoResolver();
Long beanInstance = 1L;
Long beanInstance = new Long(1);
BeanWiringInfo info = resolver.resolveWiringInfo(beanInstance);
assertThat(info).isNotNull();
assertThat(info.getBeanName()).as("Not resolving bean name to the class name of the supplied bean instance as per class contract.").isEqualTo(beanInstance.getClass().getName());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 static org.assertj.core.api.Assertions.within;
* @author Chris Beams
* @since 10.06.2003
*/
class CustomEditorTests {
public class CustomEditorTests {
@Test
void testComplexObject() {
public void testComplexObject() {
TestBean tb = new TestBean();
String newName = "Rod";
String tbString = "Kerry_34";
@@ -80,12 +80,12 @@ class CustomEditorTests {
pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
pvs.addPropertyValue(new PropertyValue("spouse", tbString));
bw.setPropertyValues(pvs);
assertThat(tb.getSpouse()).as("spouse is non-null").isNotNull();
assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue();
assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue();
}
@Test
void testComplexObjectWithOldValueAccess() {
public void testComplexObjectWithOldValueAccess() {
TestBean tb = new TestBean();
String newName = "Rod";
String tbString = "Kerry_34";
@@ -100,7 +100,7 @@ class CustomEditorTests {
pvs.addPropertyValue(new PropertyValue("spouse", tbString));
bw.setPropertyValues(pvs);
assertThat(tb.getSpouse()).as("spouse is non-null").isNotNull();
assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue();
assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue();
ITestBean spouse = tb.getSpouse();
@@ -109,7 +109,7 @@ class CustomEditorTests {
}
@Test
void testCustomEditorForSingleProperty() {
public void testCustomEditorForSingleProperty() {
TestBean tb = new TestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
@@ -127,7 +127,7 @@ class CustomEditorTests {
}
@Test
void testCustomEditorForAllStringProperties() {
public void testCustomEditorForAllStringProperties() {
TestBean tb = new TestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
@@ -145,7 +145,7 @@ class CustomEditorTests {
}
@Test
void testCustomEditorForSingleNestedProperty() {
public void testCustomEditorForSingleNestedProperty() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -164,7 +164,7 @@ class CustomEditorTests {
}
@Test
void testCustomEditorForAllNestedStringProperties() {
public void testCustomEditorForAllNestedStringProperties() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -183,7 +183,7 @@ class CustomEditorTests {
}
@Test
void testDefaultBooleanEditorForPrimitiveType() {
public void testDefaultBooleanEditorForPrimitiveType() {
BooleanTestBean tb = new BooleanTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -229,7 +229,7 @@ class CustomEditorTests {
}
@Test
void testDefaultBooleanEditorForWrapperType() {
public void testDefaultBooleanEditorForWrapperType() {
BooleanTestBean tb = new BooleanTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -239,28 +239,28 @@ class CustomEditorTests {
bw.setPropertyValue("bool2", "false");
assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue();
boolean condition3 = !tb.getBool2();
boolean condition3 = !tb.getBool2().booleanValue();
assertThat(condition3).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "on");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "off");
boolean condition2 = !tb.getBool2();
boolean condition2 = !tb.getBool2().booleanValue();
assertThat(condition2).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "yes");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "no");
boolean condition1 = !tb.getBool2();
boolean condition1 = !tb.getBool2().booleanValue();
assertThat(condition1).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "1");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "0");
boolean condition = !tb.getBool2();
boolean condition = !tb.getBool2().booleanValue();
assertThat(condition).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "");
@@ -268,7 +268,7 @@ class CustomEditorTests {
}
@Test
void testCustomBooleanEditorWithAllowEmpty() {
public void testCustomBooleanEditorWithAllowEmpty() {
BooleanTestBean tb = new BooleanTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
@@ -279,37 +279,37 @@ class CustomEditorTests {
bw.setPropertyValue("bool2", "false");
assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue();
boolean condition3 = !tb.getBool2();
boolean condition3 = !tb.getBool2().booleanValue();
assertThat(condition3).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "on");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "off");
boolean condition2 = !tb.getBool2();
boolean condition2 = !tb.getBool2().booleanValue();
assertThat(condition2).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "yes");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "no");
boolean condition1 = !tb.getBool2();
boolean condition1 = !tb.getBool2().booleanValue();
assertThat(condition1).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "1");
assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "0");
boolean condition = !tb.getBool2();
boolean condition = !tb.getBool2().booleanValue();
assertThat(condition).as("Correct bool2 value").isTrue();
bw.setPropertyValue("bool2", "");
assertThat(bw.getPropertyValue("bool2")).as("Correct bool2 value").isNull();
assertThat(tb.getBool2()).as("Correct bool2 value").isNull();
assertThat(bw.getPropertyValue("bool2") == null).as("Correct bool2 value").isTrue();
assertThat(tb.getBool2() == null).as("Correct bool2 value").isTrue();
}
@Test
void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Exception {
public void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Exception {
String trueString = "pechorin";
String falseString = "nash";
@@ -333,7 +333,7 @@ class CustomEditorTests {
}
@Test
void testDefaultNumberEditor() {
public void testDefaultNumberEditor() {
NumberTestBean tb = new NumberTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -350,34 +350,34 @@ class CustomEditorTests {
bw.setPropertyValue("double2", "6.1");
bw.setPropertyValue("bigDecimal", "4.5");
assertThat(Short.valueOf("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue();
assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue();
assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue();
assertThat(Short.valueOf("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue();
assertThat(Short.valueOf("2").equals(tb.getShort2())).as("Correct short2 value").isTrue();
assertThat(Integer.valueOf("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue();
assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue();
assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue();
assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue();
assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue();
assertThat(Integer.valueOf("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue();
assertThat(Integer.valueOf("8").equals(tb.getInt2())).as("Correct int2 value").isTrue();
assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue();
assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue();
assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue();
assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue();
assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue();
assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue();
assertThat(Long.valueOf("6").equals(tb.getLong2())).as("Correct long2 value").isTrue();
assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue();
assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue();
assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue();
assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue();
assertThat(Float.valueOf("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue();
assertThat(Float.valueOf("7.1").equals(tb.getFloat1())).as("Correct float1 value").isTrue();
assertThat(Float.valueOf("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue();
assertThat(Float.valueOf("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue();
assertThat(Double.valueOf("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue();
assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue();
assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue();
assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue();
assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue();
assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue();
assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue();
assertThat(Double.valueOf("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue();
assertThat(Double.valueOf("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue();
assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue();
assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue();
assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue();
assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue();
}
@Test
void testCustomNumberEditorWithoutAllowEmpty() {
public void testCustomNumberEditorWithoutAllowEmpty() {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
NumberTestBean tb = new NumberTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -407,34 +407,34 @@ class CustomEditorTests {
bw.setPropertyValue("double2", "6,1");
bw.setPropertyValue("bigDecimal", "4,5");
assertThat(bw.getPropertyValue("short1")).as("Correct short1 value").isEqualTo(Short.valueOf("1"));
assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue();
assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue();
assertThat(bw.getPropertyValue("short2")).as("Correct short2 value").isEqualTo(Short.valueOf("2"));
assertThat(tb.getShort2()).as("Correct short2 value").isEqualTo(Short.valueOf("2"));
assertThat(bw.getPropertyValue("int1")).as("Correct int1 value").isEqualTo(Integer.valueOf("7"));
assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue();
assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue();
assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue();
assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue();
assertThat(bw.getPropertyValue("int2")).as("Correct int2 value").isEqualTo(Integer.valueOf("8"));
assertThat(tb.getInt2()).as("Correct int2 value").isEqualTo(Integer.valueOf("8"));
assertThat(bw.getPropertyValue("long1")).as("Correct long1 value").isEqualTo(Long.valueOf("5"));
assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue();
assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue();
assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue();
assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue();
assertThat(bw.getPropertyValue("long2")).as("Correct long2 value").isEqualTo(Long.valueOf("6"));
assertThat(tb.getLong2()).as("Correct long2 value").isEqualTo(Long.valueOf("6"));
assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue();
assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue();
assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue();
assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue();
assertThat(bw.getPropertyValue("float1")).as("Correct float1 value").isEqualTo(Float.valueOf("7.1"));
assertThat(Float.valueOf(tb.getFloat1())).as("Correct float1 value").isEqualTo(Float.valueOf("7.1"));
assertThat(bw.getPropertyValue("float2")).as("Correct float2 value").isEqualTo(Float.valueOf("8.1"));
assertThat(tb.getFloat2()).as("Correct float2 value").isEqualTo(Float.valueOf("8.1"));
assertThat(bw.getPropertyValue("double1")).as("Correct double1 value").isEqualTo(Double.valueOf("5.1"));
assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue();
assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue();
assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue();
assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue();
assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue();
assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue();
assertThat(bw.getPropertyValue("double2")).as("Correct double2 value").isEqualTo(Double.valueOf("6.1"));
assertThat(tb.getDouble2()).as("Correct double2 value").isEqualTo(Double.valueOf("6.1"));
assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue();
assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue();
assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue();
assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue();
}
@Test
void testCustomNumberEditorWithAllowEmpty() {
public void testCustomNumberEditorWithAllowEmpty() {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
NumberTestBean tb = new NumberTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -443,10 +443,10 @@ class CustomEditorTests {
bw.setPropertyValue("long1", "5");
bw.setPropertyValue("long2", "6");
assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue();
assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue();
assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue();
assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue();
assertThat(Long.valueOf("6").equals(tb.getLong2())).as("Correct long2 value").isTrue();
assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue();
assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue();
bw.setPropertyValue("long2", "");
assertThat(bw.getPropertyValue("long2") == null).as("Correct long2 value").isTrue();
@@ -458,7 +458,7 @@ class CustomEditorTests {
}
@Test
void testCustomNumberEditorWithFrenchBigDecimal() throws Exception {
public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH);
NumberTestBean tb = new NumberTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
@@ -475,14 +475,14 @@ class CustomEditorTests {
}
@Test
void testParseShortGreaterThanMaxValueWithoutNumberFormat() {
public void testParseShortGreaterThanMaxValueWithoutNumberFormat() {
CustomNumberEditor editor = new CustomNumberEditor(Short.class, true);
assertThatExceptionOfType(NumberFormatException.class).as("greater than Short.MAX_VALUE + 1").isThrownBy(() ->
editor.setAsText(String.valueOf(Short.MAX_VALUE + 1)));
}
@Test
void testByteArrayPropertyEditor() {
public void testByteArrayPropertyEditor() {
PrimitiveArrayBean bean = new PrimitiveArrayBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("byteArray", "myvalue");
@@ -490,7 +490,7 @@ class CustomEditorTests {
}
@Test
void testCharArrayPropertyEditor() {
public void testCharArrayPropertyEditor() {
PrimitiveArrayBean bean = new PrimitiveArrayBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.setPropertyValue("charArray", "myvalue");
@@ -498,7 +498,7 @@ class CustomEditorTests {
}
@Test
void testCharacterEditor() {
public void testCharacterEditor() {
CharBean cb = new CharBean();
BeanWrapper bw = new BeanWrapperImpl(cb);
@@ -520,78 +520,78 @@ class CustomEditorTests {
}
@Test
void testCharacterEditorWithAllowEmpty() {
public void testCharacterEditorWithAllowEmpty() {
CharBean cb = new CharBean();
BeanWrapper bw = new BeanWrapperImpl(cb);
bw.registerCustomEditor(Character.class, new CharacterEditor(true));
bw.setPropertyValue("myCharacter", 'c');
assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('c'));
bw.setPropertyValue("myCharacter", new Character('c'));
assertThat(cb.getMyCharacter()).isEqualTo(new Character('c'));
bw.setPropertyValue("myCharacter", "c");
assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('c'));
assertThat(cb.getMyCharacter()).isEqualTo(new Character('c'));
bw.setPropertyValue("myCharacter", "\u0041");
assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('A'));
assertThat(cb.getMyCharacter()).isEqualTo(new Character('A'));
bw.setPropertyValue("myCharacter", " ");
assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf(' '));
assertThat(cb.getMyCharacter()).isEqualTo(new Character(' '));
bw.setPropertyValue("myCharacter", "");
assertThat(cb.getMyCharacter()).isNull();
}
@Test
void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception {
public void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception {
PropertyEditor charEditor = new CharacterEditor(false);
assertThatIllegalArgumentException().isThrownBy(() ->
charEditor.setAsText("ColdWaterCanyon"));
}
@Test
void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception {
public void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception {
PropertyEditor charEditor = new CharacterEditor(false);
assertThat(charEditor.getAsText()).isEmpty();
assertThat(charEditor.getAsText()).isEqualTo("");
charEditor = new CharacterEditor(true);
charEditor.setAsText(null);
assertThat(charEditor.getAsText()).isEmpty();
assertThat(charEditor.getAsText()).isEqualTo("");
charEditor.setAsText("");
assertThat(charEditor.getAsText()).isEmpty();
assertThat(charEditor.getAsText()).isEqualTo("");
charEditor.setAsText(" ");
assertThat(charEditor.getAsText()).isEqualTo(" ");
}
@Test
void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception {
public void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception {
PropertyEditor charEditor = new CharacterEditor(false);
assertThatIllegalArgumentException().isThrownBy(() ->
charEditor.setAsText(null));
}
@Test
void testClassEditor() {
public void testClassEditor() {
PropertyEditor classEditor = new ClassEditor();
classEditor.setAsText(TestBean.class.getName());
assertThat(classEditor.getValue()).isEqualTo(TestBean.class);
assertThat(classEditor.getAsText()).isEqualTo(TestBean.class.getName());
classEditor.setAsText(null);
assertThat(classEditor.getAsText()).isEmpty();
assertThat(classEditor.getAsText()).isEqualTo("");
classEditor.setAsText("");
assertThat(classEditor.getAsText()).isEmpty();
assertThat(classEditor.getAsText()).isEqualTo("");
classEditor.setAsText("\t ");
assertThat(classEditor.getAsText()).isEmpty();
assertThat(classEditor.getAsText()).isEqualTo("");
}
@Test
void testClassEditorWithNonExistentClass() throws Exception {
public void testClassEditorWithNonExistentClass() throws Exception {
PropertyEditor classEditor = new ClassEditor();
assertThatIllegalArgumentException().isThrownBy(() ->
classEditor.setAsText("hairdresser.on.Fire"));
}
@Test
void testClassEditorWithArray() {
public void testClassEditorWithArray() {
PropertyEditor classEditor = new ClassEditor();
classEditor.setAsText("org.springframework.beans.testfixture.beans.TestBean[]");
assertThat(classEditor.getValue()).isEqualTo(TestBean[].class);
@@ -602,7 +602,7 @@ class CustomEditorTests {
* SPR_2165 - ClassEditor is inconsistent with multidimensional arrays
*/
@Test
void testGetAsTextWithTwoDimensionalArray() throws Exception {
public void testGetAsTextWithTwoDimensionalArray() throws Exception {
String[][] chessboard = new String[8][8];
ClassEditor editor = new ClassEditor();
editor.setValue(chessboard.getClass());
@@ -613,7 +613,7 @@ class CustomEditorTests {
* SPR_2165 - ClassEditor is inconsistent with multidimensional arrays
*/
@Test
void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception {
public void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception {
String[][][][][] ridiculousChessboard = new String[8][4][0][1][3];
ClassEditor editor = new ClassEditor();
editor.setValue(ridiculousChessboard.getClass());
@@ -621,7 +621,7 @@ class CustomEditorTests {
}
@Test
void testFileEditor() {
public void testFileEditor() {
PropertyEditor fileEditor = new FileEditor();
fileEditor.setAsText("file:myfile.txt");
assertThat(fileEditor.getValue()).isEqualTo(new File("myfile.txt"));
@@ -629,7 +629,7 @@ class CustomEditorTests {
}
@Test
void testFileEditorWithRelativePath() {
public void testFileEditorWithRelativePath() {
PropertyEditor fileEditor = new FileEditor();
try {
fileEditor.setAsText("myfile.txt");
@@ -641,7 +641,7 @@ class CustomEditorTests {
}
@Test
void testFileEditorWithAbsolutePath() {
public void testFileEditorWithAbsolutePath() {
PropertyEditor fileEditor = new FileEditor();
// testing on Windows
if (new File("C:/myfile.txt").isAbsolute()) {
@@ -656,18 +656,18 @@ class CustomEditorTests {
}
@Test
void testLocaleEditor() {
public void testLocaleEditor() {
PropertyEditor localeEditor = new LocaleEditor();
localeEditor.setAsText("en_CA");
assertThat(localeEditor.getValue()).isEqualTo(Locale.CANADA);
assertThat(localeEditor.getAsText()).isEqualTo("en_CA");
localeEditor = new LocaleEditor();
assertThat(localeEditor.getAsText()).isEmpty();
assertThat(localeEditor.getAsText()).isEqualTo("");
}
@Test
void testPatternEditor() {
public void testPatternEditor() {
final String REGEX = "a.*";
PropertyEditor patternEditor = new PatternEditor();
@@ -676,15 +676,15 @@ class CustomEditorTests {
assertThat(patternEditor.getAsText()).isEqualTo(REGEX);
patternEditor = new PatternEditor();
assertThat(patternEditor.getAsText()).isEmpty();
assertThat(patternEditor.getAsText()).isEqualTo("");
patternEditor = new PatternEditor();
patternEditor.setAsText(null);
assertThat(patternEditor.getAsText()).isEmpty();
assertThat(patternEditor.getAsText()).isEqualTo("");
}
@Test
void testCustomBooleanEditor() {
public void testCustomBooleanEditor() {
CustomBooleanEditor editor = new CustomBooleanEditor(false);
editor.setAsText("true");
@@ -696,15 +696,15 @@ class CustomEditorTests {
assertThat(editor.getAsText()).isEqualTo("false");
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
assertThatIllegalArgumentException().isThrownBy(() ->
editor.setAsText(null));
}
@Test
void testCustomBooleanEditorWithEmptyAsNull() {
public void testCustomBooleanEditorWithEmptyAsNull() {
CustomBooleanEditor editor = new CustomBooleanEditor(true);
editor.setAsText("true");
@@ -716,34 +716,34 @@ class CustomEditorTests {
assertThat(editor.getAsText()).isEqualTo("false");
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testCustomDateEditor() {
public void testCustomDateEditor() {
CustomDateEditor editor = new CustomDateEditor(null, false);
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testCustomDateEditorWithEmptyAsNull() {
public void testCustomDateEditorWithEmptyAsNull() {
CustomDateEditor editor = new CustomDateEditor(null, true);
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testCustomDateEditorWithExactDateLength() {
public void testCustomDateEditorWithExactDateLength() {
int maxLength = 10;
String validDate = "01/01/2005";
String invalidDate = "01/01/05";
assertThat(validDate).hasSize(maxLength);
assertThat(invalidDate.length()).isNotEqualTo(maxLength);
assertThat(validDate.length() == maxLength).isTrue();
assertThat(invalidDate.length() == maxLength).isFalse();
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength);
editor.setAsText(validDate);
@@ -753,39 +753,39 @@ class CustomEditorTests {
}
@Test
void testCustomNumberEditor() {
public void testCustomNumberEditor() {
CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false);
editor.setAsText("5");
assertThat(editor.getValue()).isEqualTo(5);
assertThat(editor.getAsText()).isEqualTo("5");
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testCustomNumberEditorWithHex() {
public void testCustomNumberEditorWithHex() {
CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false);
editor.setAsText("0x" + Integer.toHexString(64));
assertThat(editor.getValue()).isEqualTo(64);
}
@Test
void testCustomNumberEditorWithEmptyAsNull() {
public void testCustomNumberEditorWithEmptyAsNull() {
CustomNumberEditor editor = new CustomNumberEditor(Integer.class, true);
editor.setAsText("5");
assertThat(editor.getValue()).isEqualTo(5);
assertThat(editor.getAsText()).isEqualTo("5");
editor.setAsText("");
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
editor.setValue(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testStringTrimmerEditor() {
public void testStringTrimmerEditor() {
StringTrimmerEditor editor = new StringTrimmerEditor(false);
editor.setAsText("test");
assertThat(editor.getValue()).isEqualTo("test");
@@ -795,15 +795,15 @@ class CustomEditorTests {
assertThat(editor.getAsText()).isEqualTo("test");
editor.setAsText("");
assertThat(editor.getValue()).isEqualTo("");
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
editor.setValue(null);
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
editor.setAsText(null);
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testStringTrimmerEditorWithEmptyAsNull() {
public void testStringTrimmerEditorWithEmptyAsNull() {
StringTrimmerEditor editor = new StringTrimmerEditor(true);
editor.setAsText("test");
assertThat(editor.getValue()).isEqualTo("test");
@@ -812,14 +812,14 @@ class CustomEditorTests {
assertThat(editor.getValue()).isEqualTo("test");
assertThat(editor.getAsText()).isEqualTo("test");
editor.setAsText(" ");
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
editor.setValue(null);
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testStringTrimmerEditorWithCharsToDelete() {
public void testStringTrimmerEditorWithCharsToDelete() {
StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", false);
editor.setAsText("te\ns\ft");
assertThat(editor.getValue()).isEqualTo("test");
@@ -829,13 +829,13 @@ class CustomEditorTests {
assertThat(editor.getAsText()).isEqualTo("test");
editor.setAsText("");
assertThat(editor.getValue()).isEqualTo("");
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
editor.setValue(null);
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() {
public void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() {
StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", true);
editor.setAsText("te\ns\ft");
assertThat(editor.getValue()).isEqualTo("test");
@@ -844,14 +844,14 @@ class CustomEditorTests {
assertThat(editor.getValue()).isEqualTo("test");
assertThat(editor.getAsText()).isEqualTo("test");
editor.setAsText(" \n\f ");
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getValue()).isEqualTo(null);
assertThat(editor.getAsText()).isEqualTo("");
editor.setValue(null);
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testIndexedPropertiesWithCustomEditorForType() {
public void testIndexedPropertiesWithCustomEditorForType() {
IndexedTestBean bean = new IndexedTestBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
@@ -904,7 +904,7 @@ class CustomEditorTests {
}
@Test
void testIndexedPropertiesWithCustomEditorForProperty() {
public void testIndexedPropertiesWithCustomEditorForProperty() {
IndexedTestBean bean = new IndexedTestBean(false);
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() {
@@ -971,7 +971,7 @@ class CustomEditorTests {
}
@Test
void testIndexedPropertiesWithIndividualCustomEditorForProperty() {
public void testIndexedPropertiesWithIndividualCustomEditorForProperty() {
IndexedTestBean bean = new IndexedTestBean(false);
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(String.class, "array[0].name", new PropertyEditorSupport() {
@@ -1056,7 +1056,7 @@ class CustomEditorTests {
}
@Test
void testNestedIndexedPropertiesWithCustomEditorForProperty() {
public void testNestedIndexedPropertiesWithCustomEditorForProperty() {
IndexedTestBean bean = new IndexedTestBean();
TestBean tb0 = bean.getArray()[0];
TestBean tb1 = bean.getArray()[1];
@@ -1140,7 +1140,7 @@ class CustomEditorTests {
}
@Test
void testNestedIndexedPropertiesWithIndexedCustomEditorForProperty() {
public void testNestedIndexedPropertiesWithIndexedCustomEditorForProperty() {
IndexedTestBean bean = new IndexedTestBean();
TestBean tb0 = bean.getArray()[0];
TestBean tb1 = bean.getArray()[1];
@@ -1191,7 +1191,7 @@ class CustomEditorTests {
}
@Test
void testIndexedPropertiesWithDirectAccessAndPropertyEditors() {
public void testIndexedPropertiesWithDirectAccessAndPropertyEditors() {
IndexedTestBean bean = new IndexedTestBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() {
@@ -1245,7 +1245,7 @@ class CustomEditorTests {
}
@Test
void testIndexedPropertiesWithDirectAccessAndSpecificPropertyEditors() {
public void testIndexedPropertiesWithDirectAccessAndSpecificPropertyEditors() {
IndexedTestBean bean = new IndexedTestBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(TestBean.class, "array[0]", new PropertyEditorSupport() {
@@ -1332,7 +1332,7 @@ class CustomEditorTests {
}
@Test
void testIndexedPropertiesWithListPropertyEditor() {
public void testIndexedPropertiesWithListPropertyEditor() {
IndexedTestBean bean = new IndexedTestBean();
BeanWrapper bw = new BeanWrapperImpl(bean);
bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() {
@@ -1350,7 +1350,7 @@ class CustomEditorTests {
}
@Test
void testConversionToOldCollections() throws PropertyVetoException {
public void testConversionToOldCollections() throws PropertyVetoException {
OldCollectionsBean tb = new OldCollectionsBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(Vector.class, new CustomCollectionEditor(Vector.class));
@@ -1367,7 +1367,7 @@ class CustomEditorTests {
}
@Test
void testUninitializedArrayPropertyWithCustomEditor() {
public void testUninitializedArrayPropertyWithCustomEditor() {
IndexedTestBean bean = new IndexedTestBean(false);
BeanWrapper bw = new BeanWrapperImpl(bean);
PropertyEditor pe = new CustomNumberEditor(Integer.class, true);
@@ -1383,7 +1383,7 @@ class CustomEditorTests {
}
@Test
void testArrayToArrayConversion() throws PropertyVetoException {
public void testArrayToArrayConversion() throws PropertyVetoException {
IndexedTestBean tb = new IndexedTestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(TestBean.class, new PropertyEditorSupport() {
@@ -1399,7 +1399,7 @@ class CustomEditorTests {
}
@Test
void testArrayToStringConversion() throws PropertyVetoException {
public void testArrayToStringConversion() throws PropertyVetoException {
TestBean tb = new TestBean();
BeanWrapper bw = new BeanWrapperImpl(tb);
bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
@@ -1408,16 +1408,16 @@ class CustomEditorTests {
setValue("-" + text + "-");
}
});
bw.setPropertyValue("name", new String[]{"a", "b"});
bw.setPropertyValue("name", new String[] {"a", "b"});
assertThat(tb.getName()).isEqualTo("-a,b-");
}
@Test
void testClassArrayEditorSunnyDay() throws Exception {
public void testClassArrayEditorSunnyDay() throws Exception {
ClassArrayEditor classArrayEditor = new ClassArrayEditor();
classArrayEditor.setAsText("java.lang.String,java.util.HashMap");
Class<?>[] classes = (Class<?>[]) classArrayEditor.getValue();
assertThat(classes).hasSize(2);
assertThat(classes.length).isEqualTo(2);
assertThat(classes[0]).isEqualTo(String.class);
assertThat(classes[1]).isEqualTo(HashMap.class);
assertThat(classArrayEditor.getAsText()).isEqualTo("java.lang.String,java.util.HashMap");
@@ -1426,11 +1426,11 @@ class CustomEditorTests {
}
@Test
void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception {
public void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception {
ClassArrayEditor classArrayEditor = new ClassArrayEditor();
classArrayEditor.setAsText("java.lang.String[],java.util.Map[],int[],float[][][]");
Class<?>[] classes = (Class<?>[]) classArrayEditor.getValue();
assertThat(classes).hasSize(4);
assertThat(classes.length).isEqualTo(4);
assertThat(classes[0]).isEqualTo(String[].class);
assertThat(classes[1]).isEqualTo(Map[].class);
assertThat(classes[2]).isEqualTo(int[].class);
@@ -1441,31 +1441,31 @@ class CustomEditorTests {
}
@Test
void testClassArrayEditorSetAsTextWithNull() throws Exception {
public void testClassArrayEditorSetAsTextWithNull() throws Exception {
ClassArrayEditor editor = new ClassArrayEditor();
editor.setAsText(null);
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testClassArrayEditorSetAsTextWithEmptyString() throws Exception {
public void testClassArrayEditorSetAsTextWithEmptyString() throws Exception {
ClassArrayEditor editor = new ClassArrayEditor();
editor.setAsText("");
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception {
public void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception {
ClassArrayEditor editor = new ClassArrayEditor();
editor.setAsText("\n");
assertThat(editor.getValue()).isNull();
assertThat(editor.getAsText()).isEmpty();
assertThat(editor.getAsText()).isEqualTo("");
}
@Test
void testCharsetEditor() throws Exception {
public void testCharsetEditor() throws Exception {
CharsetEditor editor = new CharsetEditor();
String name = "UTF-8";
editor.setAsText(name);
@@ -1,9 +1,9 @@
description = "Spring Context Indexer"
dependencies {
testImplementation(project(":spring-context"))
testImplementation("javax.inject:javax.inject")
testImplementation("javax.annotation:javax.annotation-api")
testImplementation("javax.transaction:javax.transaction-api")
testImplementation("org.eclipse.persistence:javax.persistence")
testCompile(project(":spring-context"))
testCompile("javax.inject:javax.inject")
testCompile("javax.annotation:javax.annotation-api")
testCompile("javax.transaction:javax.transaction-api")
testCompile("org.eclipse.persistence:javax.persistence")
}
@@ -1,9 +1,9 @@
description = "Spring Context Support"
dependencies {
api(project(":spring-beans"))
api(project(":spring-context"))
api(project(":spring-core"))
compile(project(":spring-beans"))
compile(project(":spring-context"))
compile(project(":spring-core"))
optional(project(":spring-jdbc")) // for Quartz support
optional(project(":spring-tx")) // for Quartz support
optional("javax.activation:javax.activation-api")
@@ -14,18 +14,18 @@ dependencies {
optional("org.quartz-scheduler:quartz")
optional("org.codehaus.fabric3.api:commonj")
optional("org.freemarker:freemarker")
testImplementation(project(":spring-context"))
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-context")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation(testFixtures(project(":spring-tx")))
testImplementation("org.hsqldb:hsqldb")
testImplementation("org.hibernate:hibernate-validator")
testImplementation("javax.annotation:javax.annotation-api")
testRuntimeOnly("org.ehcache:jcache")
testRuntimeOnly("org.ehcache:ehcache")
testRuntimeOnly("org.glassfish:javax.el")
testRuntimeOnly("com.sun.mail:javax.mail")
testCompile(project(":spring-context"))
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-context")))
testCompile(testFixtures(project(":spring-core")))
testCompile(testFixtures(project(":spring-tx")))
testCompile("org.hsqldb:hsqldb")
testCompile("org.hibernate:hibernate-validator")
testCompile("javax.annotation:javax.annotation-api")
testRuntime("org.ehcache:jcache")
testRuntime("org.ehcache:ehcache")
testRuntime("org.glassfish:javax.el")
testRuntime("com.sun.mail:javax.mail")
testFixturesApi("org.junit.jupiter:junit-jupiter-api")
testFixturesImplementation("org.assertj:assertj-core")
testFixturesImplementation("org.mockito:mockito-core")
+19 -19
View File
@@ -4,10 +4,10 @@ apply plugin: "groovy"
apply plugin: "kotlin"
dependencies {
api(project(":spring-aop"))
api(project(":spring-beans"))
api(project(":spring-core"))
api(project(":spring-expression"))
compile(project(":spring-aop"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
compile(project(":spring-expression"))
optional(project(":spring-instrument"))
optional("javax.annotation:javax.annotation-api")
optional("javax.ejb:javax.ejb-api")
@@ -26,22 +26,22 @@ dependencies {
optional("org.jetbrains.kotlin:kotlin-reflect")
optional("org.jetbrains.kotlin:kotlin-stdlib")
optional("org.reactivestreams:reactive-streams")
testImplementation(testFixtures(project(":spring-aop")))
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation("io.projectreactor:reactor-core")
testImplementation("org.codehaus.groovy:groovy-jsr223")
testImplementation("org.codehaus.groovy:groovy-test")
testImplementation("org.codehaus.groovy:groovy-xml")
testImplementation("org.apache.commons:commons-pool2")
testImplementation("javax.inject:javax.inject-tck")
testImplementation("org.awaitility:awaitility")
testRuntimeOnly("javax.xml.bind:jaxb-api")
testRuntimeOnly("org.glassfish:javax.el")
testCompile(testFixtures(project(":spring-aop")))
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-core")))
testCompile("io.projectreactor:reactor-core")
testCompile("org.codehaus.groovy:groovy-jsr223")
testCompile("org.codehaus.groovy:groovy-test")
testCompile("org.codehaus.groovy:groovy-xml")
testCompile("org.apache.commons:commons-pool2")
testCompile("javax.inject:javax.inject-tck")
testCompile("org.awaitility:awaitility")
testRuntime("javax.xml.bind:jaxb-api")
testRuntime("org.glassfish:javax.el")
// Substitute for javax.management:jmxremote_optional:1.0.1_04 (not available on Maven Central)
testRuntimeOnly("org.glassfish.external:opendmk_jmxremote_optional_jar")
testRuntimeOnly("org.javamoney:moneta")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine") // for @Inject TCK
testRuntime("org.glassfish.external:opendmk_jmxremote_optional_jar")
testRuntime("org.javamoney:moneta")
testRuntime("org.junit.vintage:junit-vintage-engine") // for @Inject TCK
testFixturesApi("org.junit.jupiter:junit-jupiter-api")
testFixturesImplementation(testFixtures(project(":spring-beans")))
testFixturesImplementation("com.google.code.findbugs:jsr305")
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,11 +38,9 @@ import org.springframework.core.annotation.AliasFor;
* replace the default one (see {@link #keyGenerator}).
*
* <p>If no value is found in the cache for the computed key, the target method
* will be invoked and the returned value will be stored in the associated cache.
* Note that {@link java.util.Optional} return types are unwrapped automatically.
* If an {@code Optional} value is {@linkplain java.util.Optional#isPresent()
* present}, it will be stored in the associated cache. If an {@code Optional}
* value is not present, {@code null} will be stored in the associated cache.
* will be invoked and the returned value stored in the associated cache. Note
* that Java8's {@code Optional} return types are automatically handled and its
* content is stored in the cache if present.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em> with attribute overrides.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2018 the original author 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.scheduling.config.ScheduledTaskRegistrar;
/**
* Enables Spring's scheduled task execution capability, similar to
* functionality found in Spring's {@code <task:*>} XML namespace. To be used
* on {@link Configuration @Configuration} classes as follows:
* on @{@link Configuration} classes as follows:
*
* <pre class="code">
* &#064;Configuration
@@ -41,8 +41,8 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* // various &#064;Bean definitions
* }</pre>
*
* <p>This enables detection of {@link Scheduled @Scheduled} annotations on any
* Spring-managed bean in the container. For example, given a class {@code MyTask}:
* This enables detection of @{@link Scheduled} annotations on any Spring-managed
* bean in the container. For example, given a class {@code MyTask}
*
* <pre class="code">
* package com.myco.tasks;
@@ -55,7 +55,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* }
* }</pre>
*
* <p>the following configuration would ensure that {@code MyTask.work()} is called
* the following configuration would ensure that {@code MyTask.work()} is called
* once every 1000 ms:
*
* <pre class="code">
@@ -69,7 +69,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* }
* }</pre>
*
* <p>Alternatively, if {@code MyTask} were annotated with {@code @Component}, the
* Alternatively, if {@code MyTask} were annotated with {@code @Component}, the
* following configuration would ensure that its {@code @Scheduled} method is
* invoked at the desired interval:
*
@@ -80,7 +80,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* public class AppConfig {
* }</pre>
*
* <p>Methods annotated with {@code @Scheduled} may even be declared directly within
* Methods annotated with {@code @Scheduled} may even be declared directly within
* {@code @Configuration} classes:
*
* <pre class="code">
@@ -94,7 +94,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* }
* }</pre>
*
* <p>By default, Spring will search for an associated scheduler definition: either
* <p>By default, will be searching for an associated scheduler definition: either
* a unique {@link org.springframework.scheduling.TaskScheduler} bean in the context,
* or a {@code TaskScheduler} bean named "taskScheduler" otherwise; the same lookup
* will also be performed for a {@link java.util.concurrent.ScheduledExecutorService}
@@ -141,7 +141,11 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
* taskRegistrar.setScheduler(taskScheduler());
* taskRegistrar.addTriggerTask(
* () -&gt; myTask().work(),
* new Runnable() {
* public void run() {
* myTask().work();
* }
* },
* new CustomTrigger()
* );
* }
@@ -161,7 +165,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* configuration:
*
* <pre class="code">
* &lt;beans&gt;
* &lt;beans>
*
* &lt;task:annotation-driven scheduler="taskScheduler"/&gt;
*
@@ -176,13 +180,13 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* &lt;/beans&gt;
* </pre>
*
* <p>The examples are equivalent save that in XML a <em>fixed-rate</em> period is used
* The examples are equivalent save that in XML a <em>fixed-rate</em> period is used
* instead of a custom <em>{@code Trigger}</em> implementation; this is because the
* {@code task:} namespace {@code scheduled} cannot easily expose such support. This is
* but one demonstration how the code-based approach allows for maximum configurability
* through direct access to actual componentry.
* through direct access to actual componentry.<p>
*
* <p><b>Note: {@code @EnableScheduling} applies to its local application context only,
* <b>Note: {@code @EnableScheduling} applies to its local application context only,
* allowing for selective scheduling of beans at different levels.</b> Please redeclare
* {@code @EnableScheduling} in each individual context, e.g. the common root web
* application context and any separate {@code DispatcherServlet} application contexts,
@@ -22,7 +22,6 @@ import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@@ -38,7 +37,7 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* <p>Processing of {@code @Scheduled} annotations is performed by
* registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
* done manually or, more conveniently, through the {@code <task:annotation-driven/>}
* XML element or {@link EnableScheduling @EnableScheduling} annotation.
* element or @{@link EnableScheduling} annotation.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em> with attribute overrides.
@@ -47,8 +46,6 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
* @author Juergen Hoeller
* @author Dave Syer
* @author Chris Beams
* @author Victor Brown
* @author Sam Brannen
* @since 3.0
* @see EnableScheduling
* @see ScheduledAnnotationBeanPostProcessor
@@ -104,75 +101,52 @@ public @interface Scheduled {
String zone() default "";
/**
* Execute the annotated method with a fixed period between the end of the
* last invocation and the start of the next.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the delay
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds
*/
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.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the delay as a String value &mdash; for example, a placeholder
* Execute the annotated method with a fixed period in milliseconds 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
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String fixedDelayString() default "";
/**
* Execute the annotated method with a fixed period between invocations.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the period
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds
*/
long fixedRate() default -1;
/**
* Execute the annotated method with a fixed period between invocations.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the period as a String value &mdash; for example, a placeholder
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds as a String value, e.g. a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String fixedRateString() default "";
/**
* Number of units of time to delay before the first execution of a
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate} or {@link #fixedDelay} task.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the initial
* @return the initial delay in milliseconds
* @since 3.2
*/
long initialDelay() default -1;
/**
* Number of units of time to delay before the first execution of a
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate} or {@link #fixedDelay} task.
* <p>The time unit is milliseconds by default but can be overridden via
* {@link #timeUnit}.
* @return the initial delay as a String value &mdash; for example, a placeholder
* @return the initial delay in milliseconds as a String value, e.g. a placeholder
* or a {@link java.time.Duration#parse java.time.Duration} compliant value
* @since 3.2.2
*/
String initialDelayString() default "";
/**
* The {@link TimeUnit} to use for {@link #fixedDelay}, {@link #fixedDelayString},
* {@link #fixedRate}, {@link #fixedRateString}, {@link #initialDelay}, and
* {@link #initialDelayString}.
* <p>Defaults to {@link TimeUnit#MILLISECONDS}.
* <p>This attribute is ignored for {@linkplain #cron() cron expressions}
* and for {@link java.time.Duration} values supplied via {@link #fixedDelayString},
* {@link #fixedRateString}, or {@link #initialDelayString}.
* @return the {@code TimeUnit} to use
* @since 5.3.10
*/
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}
@@ -30,7 +30,6 @@ import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -78,10 +77,9 @@ import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
/**
* Bean post-processor that registers methods annotated with
* {@link Scheduled @Scheduled} to be invoked by a
* {@link org.springframework.scheduling.TaskScheduler} according to the
* "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
* Bean post-processor that registers methods annotated with @{@link Scheduled}
* to be invoked by a {@link org.springframework.scheduling.TaskScheduler} according
* to the "fixedRate", "fixedDelay", or "cron" expression provided via the annotation.
*
* <p>This post-processor is automatically registered by Spring's
* {@code <task:annotation-driven>} XML element, and also by the
@@ -89,16 +87,13 @@ import org.springframework.util.StringValueResolver;
*
* <p>Autodetects any {@link SchedulingConfigurer} instances in the container,
* allowing for customization of the scheduler to be used or for fine-grained
* control over task registration (e.g. registration of {@link Trigger} tasks).
* See the {@link EnableScheduling @EnableScheduling} javadocs for complete usage
* details.
* control over task registration (e.g. registration of {@link Trigger} tasks.
* See the @{@link EnableScheduling} javadocs for complete usage details.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @author Elizabeth Chatman
* @author Victor Brown
* @author Sam Brannen
* @since 3.0
* @see Scheduled
* @see EnableScheduling
@@ -155,8 +150,7 @@ public class ScheduledAnnotationBeanPostProcessor
/**
* Create a {@code ScheduledAnnotationBeanPostProcessor} delegating to the
* specified {@link ScheduledTaskRegistrar}.
* @param registrar the ScheduledTaskRegistrar to register {@code @Scheduled}
* tasks on
* @param registrar the ScheduledTaskRegistrar to register @Scheduled tasks on
* @since 5.1
*/
public ScheduledAnnotationBeanPostProcessor(ScheduledTaskRegistrar registrar) {
@@ -389,7 +383,7 @@ public class ScheduledAnnotationBeanPostProcessor
/**
* Process the given {@code @Scheduled} method declaration on the given bean.
* @param scheduled the {@code @Scheduled} annotation
* @param scheduled the @Scheduled annotation
* @param method the method that the annotation has been declared on
* @param bean the target bean instance
* @see #createRunnable(Object, Method)
@@ -404,7 +398,7 @@ public class ScheduledAnnotationBeanPostProcessor
Set<ScheduledTask> tasks = new LinkedHashSet<>(4);
// Determine initial delay
long initialDelay = convertToMillis(scheduled.initialDelay(), scheduled.timeUnit());
long initialDelay = scheduled.initialDelay();
String initialDelayString = scheduled.initialDelayString();
if (StringUtils.hasText(initialDelayString)) {
Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
@@ -413,7 +407,7 @@ public class ScheduledAnnotationBeanPostProcessor
}
if (StringUtils.hasLength(initialDelayString)) {
try {
initialDelay = convertToMillis(initialDelayString, scheduled.timeUnit());
initialDelay = parseDelayAsLong(initialDelayString);
}
catch (RuntimeException ex) {
throw new IllegalArgumentException(
@@ -452,13 +446,12 @@ public class ScheduledAnnotationBeanPostProcessor
}
// Check fixed delay
long fixedDelay = convertToMillis(scheduled.fixedDelay(), scheduled.timeUnit());
long fixedDelay = scheduled.fixedDelay();
if (fixedDelay >= 0) {
Assert.isTrue(!processedSchedule, errorMessage);
processedSchedule = true;
tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
}
String fixedDelayString = scheduled.fixedDelayString();
if (StringUtils.hasText(fixedDelayString)) {
if (this.embeddedValueResolver != null) {
@@ -468,7 +461,7 @@ public class ScheduledAnnotationBeanPostProcessor
Assert.isTrue(!processedSchedule, errorMessage);
processedSchedule = true;
try {
fixedDelay = convertToMillis(fixedDelayString, scheduled.timeUnit());
fixedDelay = parseDelayAsLong(fixedDelayString);
}
catch (RuntimeException ex) {
throw new IllegalArgumentException(
@@ -479,7 +472,7 @@ public class ScheduledAnnotationBeanPostProcessor
}
// Check fixed rate
long fixedRate = convertToMillis(scheduled.fixedRate(), scheduled.timeUnit());
long fixedRate = scheduled.fixedRate();
if (fixedRate >= 0) {
Assert.isTrue(!processedSchedule, errorMessage);
processedSchedule = true;
@@ -494,7 +487,7 @@ public class ScheduledAnnotationBeanPostProcessor
Assert.isTrue(!processedSchedule, errorMessage);
processedSchedule = true;
try {
fixedRate = convertToMillis(fixedRateString, scheduled.timeUnit());
fixedRate = parseDelayAsLong(fixedRateString);
}
catch (RuntimeException ex) {
throw new IllegalArgumentException(
@@ -534,19 +527,11 @@ public class ScheduledAnnotationBeanPostProcessor
return new ScheduledMethodRunnable(target, invocableMethod);
}
private static long convertToMillis(long value, TimeUnit timeUnit) {
return TimeUnit.MILLISECONDS.convert(value, timeUnit);
}
private static long convertToMillis(String value, TimeUnit timeUnit) {
if (isDurationString(value)) {
private static long parseDelayAsLong(String value) throws RuntimeException {
if (value.length() > 1 && (isP(value.charAt(0)) || isP(value.charAt(1)))) {
return Duration.parse(value).toMillis();
}
return convertToMillis(Long.parseLong(value), timeUnit);
}
private static boolean isDurationString(String value) {
return (value.length() > 1 && (isP(value.charAt(0)) || isP(value.charAt(1))));
return Long.parseLong(value);
}
private static boolean isP(char ch) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2018 the original author 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,17 @@ package org.springframework.scheduling.annotation;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* Optional interface to be implemented by {@link
* org.springframework.context.annotation.Configuration @Configuration} classes annotated
* with {@link EnableScheduling @EnableScheduling}. Typically used for setting a specific
* Optional interface to be implemented by @{@link
* org.springframework.context.annotation.Configuration Configuration} classes annotated
* with @{@link EnableScheduling}. Typically used for setting a specific
* {@link org.springframework.scheduling.TaskScheduler TaskScheduler} bean to be used when
* executing scheduled tasks or for registering scheduled tasks in a <em>programmatic</em>
* fashion as opposed to the <em>declarative</em> approach of using the
* {@link Scheduled @Scheduled} annotation. For example, this may be necessary
* when implementing {@link org.springframework.scheduling.Trigger Trigger}-based
* tasks, which are not supported by the {@code @Scheduled} annotation.
* fashion as opposed to the <em>declarative</em> approach of using the @{@link Scheduled}
* annotation. For example, this may be necessary when implementing {@link
* org.springframework.scheduling.Trigger Trigger}-based tasks, which are not supported by
* the {@code @Scheduled} annotation.
*
* <p>See {@link EnableScheduling @EnableScheduling} for detailed usage examples.
* <p>See @{@link EnableScheduling} for detailed usage examples.
*
* @author Chris Beams
* @since 3.1
@@ -162,13 +162,13 @@ class ProceedTestingAspect implements Ordered {
public Object doubleOrQuits(ProceedingJoinPoint pjp) throws Throwable {
int value = ((Integer) pjp.getArgs()[0]).intValue();
pjp.getArgs()[0] = Integer.valueOf(value * 2);
pjp.getArgs()[0] = new Integer(value * 2);
return pjp.proceed();
}
public Object addOne(ProceedingJoinPoint pjp, Float value) throws Throwable {
float fv = value.floatValue();
return pjp.proceed(new Object[] {Float.valueOf(fv + 1.0F)});
return pjp.proceed(new Object[] {new Float(fv + 1.0F)});
}
public void captureStringArgument(JoinPoint tjp, String arg) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,8 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -38,6 +40,7 @@ import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.ITestBean;
import org.springframework.beans.testfixture.beans.TestBean;
@@ -63,6 +66,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class AspectJAutoProxyCreatorTests {
private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
@Test
public void testAspectsAreApplied() {
ClassPathXmlApplicationContext bf = newContext("aspects.xml");
@@ -79,7 +79,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Stephane Nicoll
* @author Juergen Hoeller
*/
class AnnotationDrivenEventListenerTests {
public class AnnotationDrivenEventListenerTests {
private ConfigurableApplicationContext context;
@@ -97,7 +97,7 @@ class AnnotationDrivenEventListenerTests {
@Test
void simpleEventJavaConfig() {
public void simpleEventJavaConfig() {
load(TestEventListener.class);
TestEvent event = new TestEvent(this, "test");
TestEventListener listener = this.context.getBean(TestEventListener.class);
@@ -120,7 +120,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void simpleEventXmlConfig() {
public void simpleEventXmlConfig() {
this.context = new ClassPathXmlApplicationContext(
"org/springframework/context/event/simple-event-configuration.xml");
@@ -141,7 +141,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void metaAnnotationIsDiscovered() {
public void metaAnnotationIsDiscovered() {
load(MetaAnnotationListenerTestBean.class);
MetaAnnotationListenerTestBean bean = this.context.getBean(MetaAnnotationListenerTestBean.class);
this.eventCollector.assertNoEventReceived(bean);
@@ -159,7 +159,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void contextEventsAreReceived() {
public void contextEventsAreReceived() {
load(ContextEventListener.class);
ContextEventListener listener = this.context.getBean(ContextEventListener.class);
@@ -175,7 +175,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void methodSignatureNoEvent() {
public void methodSignatureNoEvent() {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext failingContext =
new AnnotationConfigApplicationContext();
@@ -189,7 +189,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void simpleReply() {
public void simpleReply() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, "dummy");
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -204,7 +204,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void nullReplyIgnored() {
public void nullReplyIgnored() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, null); // No response
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -219,7 +219,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void arrayReply() {
public void arrayReply() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, new String[]{"first", "second"});
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -234,7 +234,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void collectionReply() {
public void collectionReply() {
load(TestEventListener.class, ReplyEventListener.class);
Set<Object> replies = new LinkedHashSet<>();
replies.add("first");
@@ -253,7 +253,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void collectionReplyNullValue() {
public void collectionReplyNullValue() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, Arrays.asList(null, "test"));
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -268,7 +268,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenableFutureReply() {
public void listenableFutureReply() {
load(TestEventListener.class, ReplyEventListener.class);
SettableListenableFuture<String> future = new SettableListenableFuture<>();
future.set("dummy");
@@ -285,7 +285,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void completableFutureReply() {
public void completableFutureReply() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, CompletableFuture.completedFuture("dummy"));
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -300,7 +300,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void monoReply() {
public void monoReply() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, Mono.just("dummy"));
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -315,7 +315,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void fluxReply() {
public void fluxReply() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, Flux.just("dummy1", "dummy2"));
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -330,7 +330,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void eventListenerWorksWithSimpleInterfaceProxy() {
public void eventListenerWorksWithSimpleInterfaceProxy() {
load(ScopedProxyTestBean.class);
SimpleService proxy = this.context.getBean(SimpleService.class);
@@ -347,7 +347,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void eventListenerWorksWithAnnotatedInterfaceProxy() {
public void eventListenerWorksWithAnnotatedInterfaceProxy() {
load(AnnotatedProxyTestBean.class);
AnnotatedSimpleService proxy = this.context.getBean(AnnotatedSimpleService.class);
@@ -364,7 +364,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void eventListenerWorksWithCglibProxy() {
public void eventListenerWorksWithCglibProxy() {
load(CglibProxyTestBean.class);
CglibProxyTestBean proxy = this.context.getBean(CglibProxyTestBean.class);
@@ -381,14 +381,14 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void privateMethodOnCglibProxyFails() {
public void privateMethodOnCglibProxyFails() {
assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(() ->
load(CglibProxyWithPrivateMethod.class))
.withCauseInstanceOf(IllegalStateException.class);
}
@Test
void eventListenerWorksWithCustomScope() {
public void eventListenerWorksWithCustomScope() {
load(CustomScopeTestBean.class);
CustomScope customScope = new CustomScope();
this.context.getBeanFactory().registerScope("custom", customScope);
@@ -417,7 +417,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void asyncProcessingApplied() throws InterruptedException {
public void asyncProcessingApplied() throws InterruptedException {
loadAsync(AsyncEventListener.class);
String threadName = Thread.currentThread().getName();
@@ -432,7 +432,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void asyncProcessingAppliedWithInterfaceProxy() throws InterruptedException {
public void asyncProcessingAppliedWithInterfaceProxy() throws InterruptedException {
doLoad(AsyncConfigurationWithInterfaces.class, SimpleProxyTestBean.class);
String threadName = Thread.currentThread().getName();
@@ -447,7 +447,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void asyncProcessingAppliedWithScopedProxy() throws InterruptedException {
public void asyncProcessingAppliedWithScopedProxy() throws InterruptedException {
doLoad(AsyncConfigurationWithInterfaces.class, ScopedProxyTestBean.class);
String threadName = Thread.currentThread().getName();
@@ -462,7 +462,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void exceptionPropagated() {
public void exceptionPropagated() {
load(ExceptionEventListener.class);
TestEvent event = new TestEvent(this, "fail");
ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class);
@@ -475,7 +475,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void exceptionNotPropagatedWithAsync() throws InterruptedException {
public void exceptionNotPropagatedWithAsync() throws InterruptedException {
loadAsync(ExceptionEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, "fail");
ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class);
@@ -489,7 +489,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenerWithSimplePayload() {
public void listenerWithSimplePayload() {
load(TestEventListener.class);
TestEventListener listener = this.context.getBean(TestEventListener.class);
@@ -500,7 +500,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenerWithNonMatchingPayload() {
public void listenerWithNonMatchingPayload() {
load(TestEventListener.class);
TestEventListener listener = this.context.getBean(TestEventListener.class);
@@ -511,7 +511,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void replyWithPayload() {
public void replyWithPayload() {
load(TestEventListener.class, ReplyEventListener.class);
AnotherTestEvent event = new AnotherTestEvent(this, "String");
ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class);
@@ -527,7 +527,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenerWithGenericApplicationEvent() {
public void listenerWithGenericApplicationEvent() {
load(GenericEventListener.class);
GenericEventListener listener = this.context.getBean(GenericEventListener.class);
@@ -538,7 +538,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenerWithResolvableTypeEvent() {
public void listenerWithResolvableTypeEvent() {
load(ResolvableTypeEventListener.class);
ResolvableTypeEventListener listener = this.context.getBean(ResolvableTypeEventListener.class);
@@ -550,7 +550,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void listenerWithResolvableTypeEventWrongGeneric() {
public void listenerWithResolvableTypeEventWrongGeneric() {
load(ResolvableTypeEventListener.class);
ResolvableTypeEventListener listener = this.context.getBean(ResolvableTypeEventListener.class);
@@ -562,12 +562,12 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void conditionMatch() {
public void conditionMatch() {
validateConditionMatch(ConditionalEventListener.class);
}
@Test
void conditionMatchWithProxy() {
public void conditionMatchWithProxy() {
validateConditionMatch(ConditionalEventListener.class, MethodValidationPostProcessor.class);
}
@@ -600,7 +600,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void conditionDoesNotMatch() {
public void conditionDoesNotMatch() {
long maxLong = Long.MAX_VALUE;
load(ConditionalEventListener.class);
TestEvent event = new TestEvent(this, "KO");
@@ -625,7 +625,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void orderedListeners() {
public void orderedListeners() {
load(OrderedTestListener.class);
OrderedTestListener listener = this.context.getBean(OrderedTestListener.class);
@@ -635,7 +635,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test @Disabled // SPR-15122
void listenersReceiveEarlyEvents() {
public void listenersReceiveEarlyEvents() {
load(EventOnPostConstruct.class, OrderedTestListener.class);
OrderedTestListener listener = this.context.getBean(OrderedTestListener.class);
@@ -643,7 +643,7 @@ class AnnotationDrivenEventListenerTests {
}
@Test
void missingListenerBeanIgnored() {
public void missingListenerBeanIgnored() {
load(MissingEventListener.class);
context.getBean(UseMissingEventListener.class);
context.getBean(ApplicationEventMulticaster.class).multicastEvent(new TestEvent(this));
@@ -697,7 +697,7 @@ class AnnotationDrivenEventListenerTests {
static class TestConditionEvaluator {
public boolean valid(Double ratio) {
return Double.valueOf(42).equals(ratio);
return new Double(42).equals(ratio);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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,6 +28,8 @@ import java.security.Permission;
import java.util.Optional;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectFactory;
@@ -38,6 +40,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.Scope;
import org.springframework.beans.factory.config.TypedStringValue;
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.beans.testfixture.beans.TestBean;
@@ -61,6 +64,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class ApplicationContextExpressionTests {
private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
@Test
@SuppressWarnings("deprecation")
void genericApplicationContext() throws Exception {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -341,10 +341,10 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
assertIsRegistered("Bean instance not registered", objectName);
Object result = server.invoke(objectName, "add", new Object[] {2, 3}, new String[] {
Object result = server.invoke(objectName, "add", new Object[] {new Integer(2), new Integer(3)}, new String[] {
int.class.getName(), int.class.getName()});
assertThat(Integer.valueOf(5)).as("Incorrect result return from add").isEqualTo(result);
assertThat(new Integer(5)).as("Incorrect result return from add").isEqualTo(result);
assertThat(server.getAttribute(objectName, "Name")).as("Incorrect attribute value").isEqualTo(name);
server.setAttribute(objectName, new Attribute("Name", otherName));
@@ -352,7 +352,7 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
}
@Test
void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() {
void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
factory.registerBeanDefinition("^&_invalidObjectName_(*", builder.getBeanDefinition());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -60,7 +60,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
IJmxTestBean bean = getBean();
assertThat(bean).isNotNull();
MBeanInfo inf = getMBeanInfo();
assertThat(inf.getOperations()).as("Incorrect number of operations registered").hasSize(getExpectedOperationCount());
assertThat(inf.getOperations().length).as("Incorrect number of operations registered").isEqualTo(getExpectedOperationCount());
}
@Test
@@ -68,7 +68,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
IJmxTestBean bean = getBean();
assertThat(bean).isNotNull();
MBeanInfo inf = getMBeanInfo();
assertThat(inf.getAttributes()).as("Incorrect number of attributes registered").hasSize(getExpectedAttributeCount());
assertThat(inf.getAttributes().length).as("Incorrect number of attributes registered").isEqualTo(getExpectedAttributeCount());
}
@Test
@@ -81,7 +81,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
public void testGetMBeanAttributeInfo() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanAttributeInfo[] inf = info.getAttributes();
assertThat(inf).as("Invalid number of Attributes returned").hasSize(getExpectedAttributeCount());
assertThat(inf.length).as("Invalid number of Attributes returned").isEqualTo(getExpectedAttributeCount());
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull();
@@ -93,7 +93,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
public void testGetMBeanOperationInfo() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanOperationInfo[] inf = info.getOperations();
assertThat(inf).as("Invalid number of Operations returned").hasSize(getExpectedOperationCount());
assertThat(inf.length).as("Invalid number of Operations returned").isEqualTo(getExpectedOperationCount());
for (int x = 0; x < inf.length; x++) {
assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull();
@@ -128,8 +128,8 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
public void testOperationInvocation() throws Exception{
ObjectName objectName = ObjectNameManager.getInstance(getObjectName());
Object result = getServer().invoke(objectName, "add",
new Object[] {20, 30}, new String[] {"int", "int"});
assertThat(result).as("Incorrect result").isEqualTo(50);
new Object[] {new Integer(20), new Integer(30)}, new String[] {"int", "int"});
assertThat(result).as("Incorrect result").isEqualTo(new Integer(50));
}
@Test
@@ -150,12 +150,12 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
ModelMBeanOperationInfo get = info.getOperation("getName");
assertThat(get).as("get operation should not be null").isNotNull();
assertThat(Integer.valueOf(4)).as("get operation should have visibility of four").isEqualTo(get.getDescriptor().getFieldValue("visibility"));
assertThat(new Integer(4)).as("get operation should have visibility of four").isEqualTo(get.getDescriptor().getFieldValue("visibility"));
assertThat(get.getDescriptor().getFieldValue("role")).as("get operation should have role \"getter\"").isEqualTo("getter");
ModelMBeanOperationInfo set = info.getOperation("setName");
assertThat(set).as("set operation should not be null").isNotNull();
assertThat(Integer.valueOf(4)).as("set operation should have visibility of four").isEqualTo(set.getDescriptor().getFieldValue("visibility"));
assertThat(new Integer(4)).as("set operation should have visibility of four").isEqualTo(set.getDescriptor().getFieldValue("visibility"));
assertThat(set.getDescriptor().getFieldValue("role")).as("set operation should have role \"setter\"").isEqualTo("setter");
}
@@ -163,12 +163,12 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests {
public void testNotificationMetadata() throws Exception {
ModelMBeanInfo info = (ModelMBeanInfo) getMBeanInfo();
MBeanNotificationInfo[] notifications = info.getNotifications();
assertThat(notifications).as("Incorrect number of notifications").hasSize(1);
assertThat(notifications.length).as("Incorrect number of notifications").isEqualTo(1);
assertThat(notifications[0].getName()).as("Incorrect notification name").isEqualTo("My Notification");
String[] notifTypes = notifications[0].getNotifTypes();
assertThat(notifTypes).as("Incorrect number of notification types").hasSize(2);
assertThat(notifTypes.length).as("Incorrect number of notification types").isEqualTo(2);
assertThat(notifTypes[0]).as("Notification type.foo not found").isEqualTo("type.foo");
assertThat(notifTypes[1]).as("Notification type.bar not found").isEqualTo("type.bar");
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,16 +29,9 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ArgumentConversionException;
import org.junit.jupiter.params.converter.ArgumentConverter;
import org.junit.jupiter.params.converter.ConvertWith;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.scope.ScopedProxyUtils;
@@ -67,37 +60,29 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.SoftAssertions.assertSoftly;
/**
* Tests for {@link ScheduledAnnotationBeanPostProcessor}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @author Sam Brannen
* @author Stevo Slavić
* @author Victor Brown
*/
class ScheduledAnnotationBeanPostProcessorTests {
public class ScheduledAnnotationBeanPostProcessorTests {
private final StaticApplicationContext context = new StaticApplicationContext();
@AfterEach
void closeContextAfterTest() {
public void closeContextAfterTest() {
context.close();
}
@ParameterizedTest
@CsvSource({
"FixedDelay, 5000",
"FixedDelayInSeconds, 5000",
"FixedDelayInMinutes, 180000"
})
void fixedDelayTask(@NameToClass Class<?> beanClass, long expectedInterval) {
@Test
public void fixedDelayTask() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(beanClass);
BeanDefinition targetDefinition = new RootBeanDefinition(FixedDelayTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
@@ -111,7 +96,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
@SuppressWarnings("unchecked")
List<IntervalTask> fixedDelayTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks");
assertThat(fixedDelayTasks).hasSize(1);
assertThat(fixedDelayTasks.size()).isEqualTo(1);
IntervalTask task = fixedDelayTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
@@ -119,109 +104,95 @@ class ScheduledAnnotationBeanPostProcessorTests {
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedDelay");
assertThat(task.getInitialDelay()).isEqualTo(0L);
assertThat(task.getInterval()).isEqualTo(expectedInterval);
}
@ParameterizedTest
@CsvSource({
"FixedRate, 3000",
"FixedRateInSeconds, 5000",
"FixedRateInMinutes, 180000"
})
void fixedRateTask(@NameToClass Class<?> beanClass, long expectedInterval) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(beanClass);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1);
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertThat(fixedRateTasks.size()).isEqualTo(1);
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedRate");
assertSoftly(softly -> {
softly.assertThat(task.getInitialDelay()).as("initial delay").isEqualTo(0);
softly.assertThat(task.getInterval()).as("interval").isEqualTo(expectedInterval);
});
}
@ParameterizedTest
@CsvSource({
"FixedRateWithInitialDelay, 1000, 3000",
"FixedRateWithInitialDelayInSeconds, 5000, 3000",
"FixedRateWithInitialDelayInMinutes, 60000, 180000"
})
void fixedRateTaskWithInitialDelay(@NameToClass Class<?> beanClass, long expectedInitialDelay, long expectedInterval) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(beanClass);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1);
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertThat(fixedRateTasks.size()).isEqualTo(1);
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedRate");
assertSoftly(softly -> {
softly.assertThat(task.getInitialDelay()).as("initial delay").isEqualTo(expectedInitialDelay);
softly.assertThat(task.getInterval()).as("interval").isEqualTo(expectedInterval);
});
assertThat(task.getInterval()).isEqualTo(5000L);
}
@Test
void severalFixedRatesWithRepeatedScheduledAnnotation() {
public void fixedRateTask() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1);
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertThat(fixedRateTasks.size()).isEqualTo(1);
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedRate");
assertThat(task.getInitialDelay()).isEqualTo(0L);
assertThat(task.getInterval()).isEqualTo(3000L);
}
@Test
public void fixedRateTaskWithInitialDelay() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateWithInitialDelayTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
assertThat(postProcessor.getScheduledTasks().size()).isEqualTo(1);
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertThat(fixedRateTasks.size()).isEqualTo(1);
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedRate");
assertThat(task.getInitialDelay()).isEqualTo(1000L);
assertThat(task.getInterval()).isEqualTo(3000L);
}
@Test
public void severalFixedRatesWithRepeatedScheduledAnnotation() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean.class);
severalFixedRates(context, processorDefinition, targetDefinition);
}
@Test
void severalFixedRatesWithSchedulesContainerAnnotation() {
public void severalFixedRatesWithSchedulesContainerAnnotation() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(SeveralFixedRatesWithSchedulesContainerAnnotationTestBean.class);
severalFixedRates(context, processorDefinition, targetDefinition);
}
@Test
void severalFixedRatesOnBaseClass() {
public void severalFixedRatesOnBaseClass() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(FixedRatesSubBean.class);
severalFixedRates(context, processorDefinition, targetDefinition);
}
@Test
void severalFixedRatesOnDefaultMethod() {
public void severalFixedRatesOnDefaultMethod() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(FixedRatesDefaultBean.class);
severalFixedRates(context, processorDefinition, targetDefinition);
}
@Test
void severalFixedRatesAgainstNestedCglibProxy() {
public void severalFixedRatesAgainstNestedCglibProxy() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean.class);
targetDefinition.setFactoryMethodName("nestedProxy");
@@ -264,7 +235,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void cronTask() {
public void cronTask() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(CronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -291,7 +262,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void cronTaskWithZone() {
public void cronTaskWithZone() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(CronWithTimezoneTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -337,7 +308,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void cronTaskWithInvalidZone() {
public void cronTaskWithInvalidZone() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(CronWithInvalidTimezoneTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -347,7 +318,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void cronTaskWithMethodValidation() {
public void cronTaskWithMethodValidation() {
BeanDefinition validationDefinition = new RootBeanDefinition(MethodValidationPostProcessor.class);
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(CronTestBean.class);
@@ -359,7 +330,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void cronTaskWithScopedProxy() {
public void cronTaskWithScopedProxy() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
@@ -384,7 +355,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void metaAnnotationWithFixedRate() {
public void metaAnnotationWithFixedRate() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationFixedRateTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -411,7 +382,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void composedAnnotationWithInitialDelayAndFixedRate() {
public void composedAnnotationWithInitialDelayAndFixedRate() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(ComposedAnnotationFixedRateTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -439,7 +410,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void metaAnnotationWithCronExpression() {
public void metaAnnotationWithCronExpression() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationCronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -466,7 +437,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void propertyPlaceholderWithCron() {
public void propertyPlaceholderWithCron() {
String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
@@ -499,7 +470,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void propertyPlaceholderWithInactiveCron() {
public void propertyPlaceholderWithInactiveCron() {
String businessHoursCronExpression = "-";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
@@ -516,23 +487,24 @@ class ScheduledAnnotationBeanPostProcessorTests {
assertThat(postProcessor.getScheduledTasks().isEmpty()).isTrue();
}
@ParameterizedTest
@CsvSource({
"PropertyPlaceholderWithFixedDelay, 5000, 1000, 5000, 1000",
"PropertyPlaceholderWithFixedDelay, PT5S, PT1S, 5000, 1000",
"PropertyPlaceholderWithFixedDelayInSeconds, 5000, 1000, 5000000, 1000000",
"PropertyPlaceholderWithFixedDelayInSeconds, PT5S, PT1S, 5000, 1000"
})
void propertyPlaceholderWithFixedDelay(@NameToClass Class<?> beanClass, String fixedDelay, String initialDelay,
long expectedInterval, long expectedInitialDelay) {
@Test
public void propertyPlaceholderWithFixedDelayInMillis() {
propertyPlaceholderWithFixedDelay(false);
}
@Test
public void propertyPlaceholderWithFixedDelayInDuration() {
propertyPlaceholderWithFixedDelay(true);
}
private void propertyPlaceholderWithFixedDelay(boolean durationFormat) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("fixedDelay", fixedDelay);
properties.setProperty("initialDelay", initialDelay);
properties.setProperty("fixedDelay", (durationFormat ? "PT5S" : "5000"));
properties.setProperty("initialDelay", (durationFormat ? "PT1S" : "1000"));
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(beanClass);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedDelayTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("placeholder", placeholderDefinition);
context.registerBeanDefinition("target", targetDefinition);
@@ -554,29 +526,28 @@ class ScheduledAnnotationBeanPostProcessorTests {
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedDelay");
assertSoftly(softly -> {
softly.assertThat(task.getInitialDelay()).as("initial delay").isEqualTo(expectedInitialDelay);
softly.assertThat(task.getInterval()).as("interval").isEqualTo(expectedInterval);
});
assertThat(task.getInitialDelay()).isEqualTo(1000L);
assertThat(task.getInterval()).isEqualTo(5000L);
}
@ParameterizedTest
@CsvSource({
"PropertyPlaceholderWithFixedRate, 3000, 1000, 3000, 1000",
"PropertyPlaceholderWithFixedRate, PT3S, PT1S, 3000, 1000",
"PropertyPlaceholderWithFixedRateInSeconds, 3000, 1000, 3000000, 1000000",
"PropertyPlaceholderWithFixedRateInSeconds, PT3S, PT1S, 3000, 1000"
})
void propertyPlaceholderWithFixedRate(@NameToClass Class<?> beanClass, String fixedRate, String initialDelay,
long expectedInterval, long expectedInitialDelay) {
@Test
public void propertyPlaceholderWithFixedRateInMillis() {
propertyPlaceholderWithFixedRate(false);
}
@Test
public void propertyPlaceholderWithFixedRateInDuration() {
propertyPlaceholderWithFixedRate(true);
}
private void propertyPlaceholderWithFixedRate(boolean durationFormat) {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
Properties properties = new Properties();
properties.setProperty("fixedRate", fixedRate);
properties.setProperty("initialDelay", initialDelay);
properties.setProperty("fixedRate", (durationFormat ? "PT3S" : "3000"));
properties.setProperty("initialDelay", (durationFormat ? "PT1S" : "1000"));
placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
BeanDefinition targetDefinition = new RootBeanDefinition(beanClass);
BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedRateTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("placeholder", placeholderDefinition);
context.registerBeanDefinition("target", targetDefinition);
@@ -598,14 +569,12 @@ class ScheduledAnnotationBeanPostProcessorTests {
Method targetMethod = runnable.getMethod();
assertThat(targetObject).isEqualTo(target);
assertThat(targetMethod.getName()).isEqualTo("fixedRate");
assertSoftly(softly -> {
softly.assertThat(task.getInitialDelay()).as("initial delay").isEqualTo(expectedInitialDelay);
softly.assertThat(task.getInterval()).as("interval").isEqualTo(expectedInterval);
});
assertThat(task.getInitialDelay()).isEqualTo(1000L);
assertThat(task.getInterval()).isEqualTo(3000L);
}
@Test
void expressionWithCron() {
public void expressionWithCron() {
String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(ExpressionWithCronTestBean.class);
@@ -636,7 +605,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void propertyPlaceholderForMetaAnnotation() {
public void propertyPlaceholderForMetaAnnotation() {
String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertySourcesPlaceholderConfigurer.class);
@@ -669,7 +638,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void nonVoidReturnType() {
public void nonVoidReturnType() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(NonVoidReturnTypeTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -696,7 +665,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void emptyAnnotation() {
public void emptyAnnotation() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(EmptyAnnotationTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -706,7 +675,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void invalidCron() throws Throwable {
public void invalidCron() throws Throwable {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(InvalidCronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -716,7 +685,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
@Test
void nonEmptyParamList() {
public void nonEmptyParamList() {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(NonEmptyParamListTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
@@ -726,68 +695,26 @@ class ScheduledAnnotationBeanPostProcessorTests {
}
static class FixedDelay {
static class FixedDelayTestBean {
@Scheduled(fixedDelay = 5000)
void fixedDelay() {
}
}
static class FixedDelayInSeconds {
@Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS)
void fixedDelay() {
}
}
static class FixedDelayInMinutes {
@Scheduled(fixedDelay = 3, timeUnit = TimeUnit.MINUTES)
void fixedDelay() {
public void fixedDelay() {
}
}
static class FixedRate {
static class FixedRateTestBean {
@Scheduled(fixedRate = 3000)
void fixedRate() {
}
}
static class FixedRateInSeconds {
@Scheduled(fixedRate = 5, timeUnit = TimeUnit.SECONDS)
void fixedRate() {
}
}
static class FixedRateInMinutes {
@Scheduled(fixedRate = 3, timeUnit = TimeUnit.MINUTES)
void fixedRate() {
public void fixedRate() {
}
}
static class FixedRateWithInitialDelay {
static class FixedRateWithInitialDelayTestBean {
@Scheduled(fixedRate = 3000, initialDelay = 1000)
void fixedRate() {
}
}
static class FixedRateWithInitialDelayInSeconds {
@Scheduled(fixedRate = 3, initialDelay = 5, timeUnit = TimeUnit.SECONDS)
void fixedRate() {
}
}
static class FixedRateWithInitialDelayInMinutes {
@Scheduled(fixedRate = 3, initialDelay = 1, timeUnit = TimeUnit.MINUTES)
void fixedRate() {
public void fixedRate() {
}
}
@@ -795,7 +722,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class SeveralFixedRatesWithSchedulesContainerAnnotationTestBean {
@Schedules({@Scheduled(fixedRate = 4000), @Scheduled(fixedRate = 4000, initialDelay = 2000)})
void fixedRate() {
public void fixedRate() {
}
}
@@ -804,7 +731,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
@Scheduled(fixedRate = 4000)
@Scheduled(fixedRate = 4000, initialDelay = 2000)
void fixedRate() {
public void fixedRate() {
}
static SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean nestedProxy() {
@@ -821,7 +748,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
@Scheduled(fixedRate = 4000)
@Scheduled(fixedRate = 4000, initialDelay = 2000)
void fixedRate() {
public void fixedRate() {
}
}
@@ -865,7 +792,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class CronWithInvalidTimezoneTestBean {
@Scheduled(cron = "0 0 0-4,6-23 * * ?", zone = "FOO")
void cron() throws IOException {
public void cron() throws IOException {
throw new IOException("no no no");
}
}
@@ -876,7 +803,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class ProxiedCronTestBean {
@Scheduled(cron = "*/7 * * * * ?")
void cron() throws IOException {
public void cron() throws IOException {
throw new IOException("no no no");
}
}
@@ -884,7 +811,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class ProxiedCronTestBeanDependent {
ProxiedCronTestBeanDependent(ProxiedCronTestBean testBean) {
public ProxiedCronTestBeanDependent(ProxiedCronTestBean testBean) {
}
}
@@ -892,7 +819,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class NonVoidReturnTypeTestBean {
@Scheduled(cron = "0 0 9-17 * * MON-FRI")
String cron() {
public String cron() {
return "oops";
}
}
@@ -901,7 +828,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class EmptyAnnotationTestBean {
@Scheduled
void invalid() {
public void invalid() {
}
}
@@ -909,7 +836,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class InvalidCronTestBean {
@Scheduled(cron = "abc")
void invalid() {
public void invalid() {
}
}
@@ -917,7 +844,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class NonEmptyParamListTestBean {
@Scheduled(fixedRate = 3000)
void invalid(String oops) {
public void invalid(String oops) {
}
}
@@ -949,7 +876,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class MetaAnnotationFixedRateTestBean {
@EveryFiveSeconds
void checkForUpdates() {
public void checkForUpdates() {
}
}
@@ -957,7 +884,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class ComposedAnnotationFixedRateTestBean {
@WaitASec(fixedRate = 5000)
void checkForUpdates() {
public void checkForUpdates() {
}
}
@@ -965,7 +892,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class MetaAnnotationCronTestBean {
@Hourly
void generateReport() {
public void generateReport() {
}
}
@@ -973,37 +900,23 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class PropertyPlaceholderWithCronTestBean {
@Scheduled(cron = "${schedules.businessHours}")
void x() {
public void x() {
}
}
static class PropertyPlaceholderWithFixedDelay {
static class PropertyPlaceholderWithFixedDelayTestBean {
@Scheduled(fixedDelayString = "${fixedDelay}", initialDelayString = "${initialDelay}")
void fixedDelay() {
}
}
static class PropertyPlaceholderWithFixedDelayInSeconds {
@Scheduled(fixedDelayString = "${fixedDelay}", initialDelayString = "${initialDelay}", timeUnit = TimeUnit.SECONDS)
void fixedDelay() {
public void fixedDelay() {
}
}
static class PropertyPlaceholderWithFixedRate {
static class PropertyPlaceholderWithFixedRateTestBean {
@Scheduled(fixedRateString = "${fixedRate}", initialDelayString = "${initialDelay}")
void fixedRate() {
}
}
static class PropertyPlaceholderWithFixedRateInSeconds {
@Scheduled(fixedRateString = "${fixedRate}", initialDelayString = "${initialDelay}", timeUnit = TimeUnit.SECONDS)
void fixedRate() {
public void fixedRate() {
}
}
@@ -1011,7 +924,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class ExpressionWithCronTestBean {
@Scheduled(cron = "#{schedules.businessHours}")
void x() {
public void x() {
}
}
@@ -1026,24 +939,7 @@ class ScheduledAnnotationBeanPostProcessorTests {
static class PropertyPlaceholderMetaAnnotationTestBean {
@BusinessHours
void y() {
}
}
@Retention(RetentionPolicy.RUNTIME)
@ConvertWith(NameToClass.Converter.class)
private @interface NameToClass {
class Converter implements ArgumentConverter {
@Override
public Class<?> convert(Object beanClassName, ParameterContext context) throws ArgumentConversionException {
try {
String name = getClass().getEnclosingClass().getEnclosingClass().getName() + "$" + beanClassName;
return getClass().getClassLoader().loadClass(name);
}
catch (Exception ex) {
throw new ArgumentConversionException("Failed to convert class name to Class", ex);
}
}
public void y() {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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.springframework.core.testfixture.TestGroup.LONG_RUNNING;
* @author Chris Beams
*/
@EnabledForTestGroups(LONG_RUNNING)
class ScriptFactoryPostProcessorTests {
public class ScriptFactoryPostProcessorTests {
private static final String MESSAGE_TEXT = "Bingo";
@@ -79,18 +79,18 @@ class ScriptFactoryPostProcessorTests {
@Test
void testDoesNothingWhenPostProcessingNonScriptFactoryTypeBeforeInstantiation() {
public void testDoesNothingWhenPostProcessingNonScriptFactoryTypeBeforeInstantiation() throws Exception {
assertThat(new ScriptFactoryPostProcessor().postProcessBeforeInstantiation(getClass(), "a.bean")).isNull();
}
@Test
void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() {
public void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() throws Exception {
assertThatIllegalStateException().isThrownBy(() ->
new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class)));
}
@Test
void testChangeScriptWithRefreshableBeanFunctionality() throws Exception {
public void testChangeScriptWithRefreshableBeanFunctionality() throws Exception {
BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true);
BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean();
@@ -111,7 +111,7 @@ class ScriptFactoryPostProcessorTests {
}
@Test
void testChangeScriptWithNoRefreshableBeanFunctionality() throws Exception {
public void testChangeScriptWithNoRefreshableBeanFunctionality() throws Exception {
BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(false);
BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean();
@@ -131,7 +131,7 @@ class ScriptFactoryPostProcessorTests {
}
@Test
void testRefreshedScriptReferencePropagatesToCollaborators() throws Exception {
public void testRefreshedScriptReferencePropagatesToCollaborators() throws Exception {
BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true);
BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean();
BeanDefinitionBuilder collaboratorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultMessengerService.class);
@@ -159,7 +159,7 @@ class ScriptFactoryPostProcessorTests {
}
@Test
void testReferencesAcrossAContainerHierarchy() throws Exception {
public void testReferencesAcrossAContainerHierarchy() throws Exception {
GenericApplicationContext businessContext = new GenericApplicationContext();
businessContext.registerBeanDefinition("messenger", BeanDefinitionBuilder.rootBeanDefinition(StubMessenger.class).getBeanDefinition());
businessContext.refresh();
@@ -175,13 +175,13 @@ class ScriptFactoryPostProcessorTests {
}
@Test
void testScriptHavingAReferenceToAnotherBean() throws Exception {
public void testScriptHavingAReferenceToAnotherBean() throws Exception {
// just tests that the (singleton) script-backed bean is able to be instantiated with references to its collaborators
new ClassPathXmlApplicationContext("org/springframework/scripting/support/groovyReferences.xml");
}
@Test
void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Exception {
public void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Exception {
BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true);
BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean();
BeanDefinitionBuilder collaboratorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultMessengerService.class);
@@ -202,12 +202,13 @@ class ScriptFactoryPostProcessorTests {
// needs The Sundays compiler; must NOT throw any exception here...
source.setScript("I keep hoping you are the same as me, and I'll send you letters and come to your house for tea");
Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME);
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(refreshedMessenger::getMessage)
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
refreshedMessenger.getMessage())
.matches(ex -> ex.contains(ScriptCompilationException.class));
}
@Test
void testPrototypeScriptedBean() throws Exception {
public void testPrototypeScriptedBean() throws Exception {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.registerBeanDefinition("messenger", BeanDefinitionBuilder.rootBeanDefinition(StubMessenger.class).getBeanDefinition());
@@ -235,7 +236,7 @@ class ScriptFactoryPostProcessorTests {
private static BeanDefinition createScriptFactoryPostProcessor(boolean isRefreshable) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ScriptFactoryPostProcessor.class);
if (isRefreshable) {
builder.addPropertyValue("defaultRefreshCheckDelay", 1L);
builder.addPropertyValue("defaultRefreshCheckDelay", new Long(1));
}
return builder.getBeanDefinition();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,17 +36,17 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Stephane Nicoll
* @since 07.03.2006
*/
class DataBinderFieldAccessTests {
public class DataBinderFieldAccessTests {
@Test
void bindingNoErrors() throws Exception {
public void bindingNoErrors() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
assertThat(binder.isIgnoreUnknownFields()).isTrue();
binder.initDirectFieldAccess();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("name", "Rod"));
pvs.addPropertyValue(new PropertyValue("age", 32));
pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));
binder.bind(pvs);
@@ -62,21 +62,21 @@ class DataBinderFieldAccessTests {
}
@Test
void bindingNoErrorsNotIgnoreUnknown() throws Exception {
public void bindingNoErrorsNotIgnoreUnknown() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
binder.initDirectFieldAccess();
binder.setIgnoreUnknownFields(false);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("name", "Rod"));
pvs.addPropertyValue(new PropertyValue("age", 32));
pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));
assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() ->
binder.bind(pvs));
}
@Test
void bindingWithErrors() throws Exception {
public void bindingWithErrors() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
binder.initDirectFieldAccess();
@@ -105,7 +105,7 @@ class DataBinderFieldAccessTests {
}
@Test
void nestedBindingWithDefaultConversionNoErrors() throws Exception {
public void nestedBindingWithDefaultConversionNoErrors() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
assertThat(binder.isIgnoreUnknownFields()).isTrue();
@@ -122,7 +122,7 @@ class DataBinderFieldAccessTests {
}
@Test
void nestedBindingWithDisabledAutoGrow() throws Exception {
public void nestedBindingWithDisabledAutoGrow() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
binder.setAutoGrowNestedPaths(false);
@@ -135,7 +135,7 @@ class DataBinderFieldAccessTests {
}
@Test
void bindingWithErrorsAndCustomEditors() throws Exception {
public void bindingWithErrorsAndCustomEditors() throws Exception {
FieldAccessBean rod = new FieldAccessBean();
DataBinder binder = new DataBinder(rod, "person");
binder.initDirectFieldAccess();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -77,10 +77,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Rob Harrop
* @author Kazuki Shimizu
*/
class DataBinderTests {
public class DataBinderTests {
@Test
void testBindingNoErrors() throws BindException {
public void testBindingNoErrors() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
assertThat(binder.isIgnoreUnknownFields()).isTrue();
@@ -115,7 +115,7 @@ class DataBinderTests {
}
@Test
void testBindingWithDefaultConversionNoErrors() throws BindException {
public void testBindingWithDefaultConversionNoErrors() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
assertThat(binder.isIgnoreUnknownFields()).isTrue();
@@ -131,7 +131,7 @@ class DataBinderTests {
}
@Test
void testNestedBindingWithDefaultConversionNoErrors() throws BindException {
public void testNestedBindingWithDefaultConversionNoErrors() throws BindException {
TestBean rod = new TestBean(new TestBean());
DataBinder binder = new DataBinder(rod, "person");
assertThat(binder.isIgnoreUnknownFields()).isTrue();
@@ -147,7 +147,7 @@ class DataBinderTests {
}
@Test
void testBindingNoErrorsNotIgnoreUnknown() {
public void testBindingNoErrorsNotIgnoreUnknown() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
binder.setIgnoreUnknownFields(false);
@@ -160,7 +160,7 @@ class DataBinderTests {
}
@Test
void testBindingNoErrorsWithInvalidField() {
public void testBindingNoErrorsWithInvalidField() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -171,7 +171,7 @@ class DataBinderTests {
}
@Test
void testBindingNoErrorsWithIgnoreInvalid() {
public void testBindingNoErrorsWithIgnoreInvalid() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
binder.setIgnoreInvalidFields(true);
@@ -183,7 +183,7 @@ class DataBinderTests {
}
@Test
void testBindingWithErrors() {
public void testBindingWithErrors() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -245,7 +245,7 @@ class DataBinderTests {
}
@Test
void testBindingWithSystemFieldError() {
public void testBindingWithSystemFieldError() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -257,7 +257,7 @@ class DataBinderTests {
}
@Test
void testBindingWithErrorsAndCustomEditors() {
public void testBindingWithErrorsAndCustomEditors() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
binder.registerCustomEditor(String.class, "touchy", new PropertyEditorSupport() {
@@ -325,7 +325,7 @@ class DataBinderTests {
}
@Test
void testBindingWithCustomEditorOnObjectField() {
public void testBindingWithCustomEditorOnObjectField() {
BeanWithObjectProperty tb = new BeanWithObjectProperty();
DataBinder binder = new DataBinder(tb);
binder.registerCustomEditor(Integer.class, "object", new CustomNumberEditor(Integer.class, true));
@@ -336,7 +336,7 @@ class DataBinderTests {
}
@Test
void testBindingWithFormatter() {
public void testBindingWithFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -349,18 +349,18 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2");
PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
assertThat(editor).isNotNull();
editor.setValue(1.4f);
editor.setValue(new Float(1.4));
assertThat(editor.getAsText()).isEqualTo("1,4");
editor = binder.getBindingResult().findEditor("myFloat", null);
assertThat(editor).isNotNull();
editor.setAsText("1,6");
assertThat(editor.getValue()).isEqualTo(1.6f);
assertThat(editor.getValue()).isEqualTo(new Float(1.6));
}
finally {
LocaleContextHolder.resetLocaleContext();
@@ -368,7 +368,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithFormatter() {
public void testBindingErrorWithFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -381,7 +381,7 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2");
assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue();
}
@@ -391,7 +391,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithParseExceptionFromFormatter() {
public void testBindingErrorWithParseExceptionFromFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -419,7 +419,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithRuntimeExceptionFromFormatter() {
public void testBindingErrorWithRuntimeExceptionFromFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -447,7 +447,7 @@ class DataBinderTests {
}
@Test
void testBindingWithFormatterAgainstList() {
public void testBindingWithFormatterAgainstList() {
BeanWithIntegerList tb = new BeanWithIntegerList();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -469,7 +469,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithFormatterAgainstList() {
public void testBindingErrorWithFormatterAgainstList() {
BeanWithIntegerList tb = new BeanWithIntegerList();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -492,7 +492,7 @@ class DataBinderTests {
}
@Test
void testBindingWithFormatterAgainstFields() {
public void testBindingWithFormatterAgainstFields() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
FormattingConversionService conversionService = new FormattingConversionService();
@@ -506,18 +506,18 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2");
PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
assertThat(editor).isNotNull();
editor.setValue(1.4f);
editor.setValue(new Float(1.4));
assertThat(editor.getAsText()).isEqualTo("1,4");
editor = binder.getBindingResult().findEditor("myFloat", null);
assertThat(editor).isNotNull();
editor.setAsText("1,6");
assertThat(editor.getValue()).isEqualTo(1.6f);
assertThat(editor.getValue()).isEqualTo(new Float(1.6));
}
finally {
LocaleContextHolder.resetLocaleContext();
@@ -525,7 +525,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithFormatterAgainstFields() {
public void testBindingErrorWithFormatterAgainstFields() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
binder.initDirectFieldAccess();
@@ -539,7 +539,7 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2");
assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue();
}
@@ -549,7 +549,7 @@ class DataBinderTests {
}
@Test
void testBindingWithCustomFormatter() {
public void testBindingWithCustomFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
binder.addCustomFormatter(new NumberStyleFormatter(), Float.class);
@@ -559,12 +559,12 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2");
PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
assertThat(editor).isNotNull();
editor.setValue(1.4f);
editor.setValue(new Float(1.4));
assertThat(editor.getAsText()).isEqualTo("1,4");
editor = binder.getBindingResult().findEditor("myFloat", null);
@@ -578,7 +578,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithCustomFormatter() {
public void testBindingErrorWithCustomFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
binder.addCustomFormatter(new NumberStyleFormatter());
@@ -588,7 +588,7 @@ class DataBinderTests {
LocaleContextHolder.setLocale(Locale.GERMAN);
try {
binder.bind(pvs);
assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f));
assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0));
assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2");
assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue();
assertThat(binder.getBindingResult().getFieldError("myFloat").getCode()).isEqualTo("typeMismatch");
@@ -599,7 +599,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithParseExceptionFromCustomFormatter() {
public void testBindingErrorWithParseExceptionFromCustomFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
@@ -624,7 +624,7 @@ class DataBinderTests {
}
@Test
void testBindingErrorWithRuntimeExceptionFromCustomFormatter() {
public void testBindingErrorWithRuntimeExceptionFromCustomFormatter() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb);
@@ -649,7 +649,7 @@ class DataBinderTests {
}
@Test
void testConversionWithInappropriateStringEditor() {
public void testConversionWithInappropriateStringEditor() {
DataBinder dataBinder = new DataBinder(null);
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
dataBinder.setConversionService(conversionService);
@@ -662,7 +662,7 @@ class DataBinderTests {
}
@Test
void testBindingWithAllowedFields() throws BindException {
public void testBindingWithAllowedFields() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod);
binder.setAllowedFields("name", "myparam");
@@ -677,7 +677,7 @@ class DataBinderTests {
}
@Test
void testBindingWithDisallowedFields() throws BindException {
public void testBindingWithDisallowedFields() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod);
binder.setDisallowedFields("age");
@@ -695,7 +695,7 @@ class DataBinderTests {
}
@Test
void testBindingWithAllowedAndDisallowedFields() throws BindException {
public void testBindingWithAllowedAndDisallowedFields() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod);
binder.setAllowedFields("name", "myparam");
@@ -709,12 +709,12 @@ class DataBinderTests {
assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue();
assertThat(rod.getAge() == 0).as("did not change age").isTrue();
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
assertThat(disallowedFields).hasSize(1);
assertThat(disallowedFields.length).isEqualTo(1);
assertThat(disallowedFields[0]).isEqualTo("age");
}
@Test
void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindException {
public void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod);
binder.setAllowedFields("name", "age");
@@ -728,12 +728,12 @@ class DataBinderTests {
assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue();
assertThat(rod.getAge() == 0).as("did not change age").isTrue();
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
assertThat(disallowedFields).hasSize(1);
assertThat(disallowedFields.length).isEqualTo(1);
assertThat(disallowedFields[0]).isEqualTo("age");
}
@Test
void testBindingWithAllowedFieldsUsingAsterisks() throws BindException {
public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
binder.setAllowedFields("nam*", "*ouchy");
@@ -750,7 +750,7 @@ class DataBinderTests {
assertThat("Rod".equals(rod.getTouchy())).as("changed touchy correctly").isTrue();
assertThat(rod.getAge() == 0).as("did not change age").isTrue();
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
assertThat(disallowedFields).hasSize(1);
assertThat(disallowedFields.length).isEqualTo(1);
assertThat(disallowedFields[0]).isEqualTo("age");
Map<?,?> m = binder.getBindingResult().getModel();
@@ -760,7 +760,7 @@ class DataBinderTests {
}
@Test
void testBindingWithAllowedAndDisallowedMapFields() throws BindException {
public void testBindingWithAllowedAndDisallowedMapFields() throws BindException {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod);
binder.setAllowedFields("someMap[key1]", "someMap[key2]");
@@ -779,7 +779,7 @@ class DataBinderTests {
assertThat(rod.getSomeMap().get("key3")).isNull();
assertThat(rod.getSomeMap().get("key4")).isNull();
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
assertThat(disallowedFields).hasSize(2);
assertThat(disallowedFields.length).isEqualTo(2);
assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key3]")).isTrue();
assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key4]")).isTrue();
}
@@ -788,7 +788,7 @@ class DataBinderTests {
* Tests for required field, both null, non-existing and empty strings.
*/
@Test
void testBindingWithRequiredFields() {
public void testBindingWithRequiredFields() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
@@ -819,7 +819,7 @@ class DataBinderTests {
}
@Test
void testBindingWithRequiredMapFields() {
public void testBindingWithRequiredMapFields() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
@@ -839,7 +839,7 @@ class DataBinderTests {
}
@Test
void testBindingWithNestedObjectCreation() {
public void testBindingWithNestedObjectCreation() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "person");
@@ -860,7 +860,7 @@ class DataBinderTests {
}
@Test
void testCustomEditorWithOldValueAccess() {
public void testCustomEditorWithOldValueAccess() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
@@ -885,7 +885,7 @@ class DataBinderTests {
}
@Test
void testCustomEditorForSingleProperty() {
public void testCustomEditorForSingleProperty() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
DataBinder binder = new DataBinder(tb, "tb");
@@ -925,7 +925,7 @@ class DataBinderTests {
}
@Test
void testCustomEditorForPrimitiveProperty() {
public void testCustomEditorForPrimitiveProperty() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
@@ -949,7 +949,7 @@ class DataBinderTests {
}
@Test
void testCustomEditorForAllStringProperties() {
public void testCustomEditorForAllStringProperties() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
@@ -981,7 +981,7 @@ class DataBinderTests {
}
@Test
void testCustomFormatterForSingleProperty() {
public void testCustomFormatterForSingleProperty() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
DataBinder binder = new DataBinder(tb, "tb");
@@ -1021,7 +1021,7 @@ class DataBinderTests {
}
@Test
void testCustomFormatterForPrimitiveProperty() {
public void testCustomFormatterForPrimitiveProperty() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
@@ -1045,7 +1045,7 @@ class DataBinderTests {
}
@Test
void testCustomFormatterForAllStringProperties() {
public void testCustomFormatterForAllStringProperties() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
@@ -1077,7 +1077,7 @@ class DataBinderTests {
}
@Test
void testJavaBeanPropertyConventions() {
public void testJavaBeanPropertyConventions() {
Book book = new Book();
DataBinder binder = new DataBinder(book);
@@ -1101,7 +1101,7 @@ class DataBinderTests {
}
@Test
void testOptionalProperty() {
public void testOptionalProperty() {
OptionalHolder bean = new OptionalHolder();
DataBinder binder = new DataBinder(bean);
binder.setConversionService(new DefaultConversionService());
@@ -1111,7 +1111,7 @@ class DataBinderTests {
pvs.add("name", null);
binder.bind(pvs);
assertThat(bean.getId()).isEqualTo("1");
assertThat(bean.getName()).isEmpty();
assertThat(bean.getName().isPresent()).isFalse();
pvs = new MutablePropertyValues();
pvs.add("id", "2");
@@ -1122,7 +1122,7 @@ class DataBinderTests {
}
@Test
void testValidatorNoErrors() throws Exception {
public void testValidatorNoErrors() throws Exception {
TestBean tb = new TestBean();
tb.setAge(33);
tb.setName("Rod");
@@ -1183,7 +1183,7 @@ class DataBinderTests {
}
@Test
void testValidatorWithErrors() {
public void testValidatorWithErrors() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
@@ -1252,7 +1252,7 @@ class DataBinderTests {
}
@Test
void testValidatorWithErrorsAndCodesPrefix() {
public void testValidatorWithErrorsAndCodesPrefix() {
TestBean tb = new TestBean();
tb.setSpouse(new TestBean());
@@ -1324,7 +1324,7 @@ class DataBinderTests {
}
@Test
void testValidatorWithNestedObjectNull() {
public void testValidatorWithNestedObjectNull() {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
Validator testValidator = new TestBeanValidator();
@@ -1343,7 +1343,7 @@ class DataBinderTests {
}
@Test
void testNestedValidatorWithoutNestedPath() {
public void testNestedValidatorWithoutNestedPath() {
TestBean tb = new TestBean();
tb.setName("XXX");
Errors errors = new BeanPropertyBindingResult(tb, "tb");
@@ -1357,13 +1357,13 @@ class DataBinderTests {
}
@Test
void testBindingStringArrayToIntegerSet() {
public void testBindingStringArrayToIntegerSet() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class) {
@Override
protected Object convertElement(Object element) {
return Integer.valueOf(element.toString());
return new Integer(element.toString());
}
});
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -1386,7 +1386,7 @@ class DataBinderTests {
}
@Test
void testBindingNullToEmptyCollection() {
public void testBindingNullToEmptyCollection() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class, true));
@@ -1400,7 +1400,7 @@ class DataBinderTests {
}
@Test
void testBindingToIndexedField() {
public void testBindingToIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() {
@@ -1439,7 +1439,7 @@ class DataBinderTests {
}
@Test
void testBindingToNestedIndexedField() {
public void testBindingToNestedIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
@@ -1470,7 +1470,7 @@ class DataBinderTests {
}
@Test
void testEditorForNestedIndexedField() {
public void testEditorForNestedIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
@@ -1496,7 +1496,7 @@ class DataBinderTests {
}
@Test
void testSpecificEditorForNestedIndexedField() {
public void testSpecificEditorForNestedIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
@@ -1522,7 +1522,7 @@ class DataBinderTests {
}
@Test
void testInnerSpecificEditorForNestedIndexedField() {
public void testInnerSpecificEditorForNestedIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
@@ -1548,7 +1548,7 @@ class DataBinderTests {
}
@Test
void testDirectBindingToIndexedField() {
public void testDirectBindingToIndexedField() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() {
@@ -1601,7 +1601,7 @@ class DataBinderTests {
}
@Test
void testDirectBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() {
public void testDirectBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(TestBean.class, "map[key0]", new PropertyEditorSupport() {
@@ -1632,7 +1632,7 @@ class DataBinderTests {
}
@Test
void testDirectBindingToEmptyIndexedFieldWithRegisteredGenericEditor() {
public void testDirectBindingToEmptyIndexedFieldWithRegisteredGenericEditor() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() {
@@ -1663,7 +1663,7 @@ class DataBinderTests {
}
@Test
void testCustomEditorWithSubclass() {
public void testCustomEditorWithSubclass() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(TestBean.class, new PropertyEditorSupport() {
@@ -1697,7 +1697,7 @@ class DataBinderTests {
}
@Test
void testBindToStringArrayWithArrayEditor() {
public void testBindToStringArrayWithArrayEditor() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(String[].class, "stringArray", new PropertyEditorSupport() {
@@ -1717,7 +1717,7 @@ class DataBinderTests {
}
@Test
void testBindToStringArrayWithComponentEditor() {
public void testBindToStringArrayWithComponentEditor() {
TestBean tb = new TestBean();
DataBinder binder = new DataBinder(tb, "tb");
binder.registerCustomEditor(String.class, "stringArray", new PropertyEditorSupport() {
@@ -1737,7 +1737,7 @@ class DataBinderTests {
}
@Test
void testBindingErrors() {
public void testBindingErrors() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -1764,7 +1764,7 @@ class DataBinderTests {
}
@Test
void testAddAllErrors() {
public void testAddAllErrors() {
TestBean rod = new TestBean();
DataBinder binder = new DataBinder(rod, "person");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -1784,7 +1784,7 @@ class DataBinderTests {
@Test
@SuppressWarnings("unchecked")
void testBindingWithResortedList() {
public void testBindingWithResortedList() {
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new DataBinder(tb, "tb");
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -1802,7 +1802,7 @@ class DataBinderTests {
}
@Test
void testRejectWithoutDefaultMessage() {
public void testRejectWithoutDefaultMessage() {
TestBean tb = new TestBean();
tb.setName("myName");
tb.setAge(99);
@@ -1820,7 +1820,7 @@ class DataBinderTests {
}
@Test
void testBindExceptionSerializable() throws Exception {
public void testBindExceptionSerializable() throws Exception {
SerializablePerson tb = new SerializablePerson();
tb.setName("myName");
tb.setAge(99);
@@ -1849,7 +1849,7 @@ class DataBinderTests {
}
@Test
void testTrackDisallowedFields() {
public void testTrackDisallowedFields() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.setAllowedFields("name", "age");
@@ -1864,12 +1864,12 @@ class DataBinderTests {
assertThat(testBean.getName()).isEqualTo(name);
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
assertThat(disallowedFields).hasSize(1);
assertThat(disallowedFields.length).isEqualTo(1);
assertThat(disallowedFields[0]).isEqualTo("beanName");
}
@Test
void testAutoGrowWithinDefaultLimit() {
public void testAutoGrowWithinDefaultLimit() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
@@ -1877,11 +1877,11 @@ class DataBinderTests {
mpvs.add("friends[4]", "");
binder.bind(mpvs);
assertThat(testBean.getFriends()).hasSize(5);
assertThat(testBean.getFriends().size()).isEqualTo(5);
}
@Test
void testAutoGrowBeyondDefaultLimit() {
public void testAutoGrowBeyondDefaultLimit() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
@@ -1894,7 +1894,7 @@ class DataBinderTests {
}
@Test
void testAutoGrowWithinCustomLimit() {
public void testAutoGrowWithinCustomLimit() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.setAutoGrowCollectionLimit(10);
@@ -1903,11 +1903,11 @@ class DataBinderTests {
mpvs.add("friends[4]", "");
binder.bind(mpvs);
assertThat(testBean.getFriends()).hasSize(5);
assertThat(testBean.getFriends().size()).isEqualTo(5);
}
@Test
void testAutoGrowBeyondCustomLimit() {
public void testAutoGrowBeyondCustomLimit() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.setAutoGrowCollectionLimit(10);
@@ -1921,7 +1921,7 @@ class DataBinderTests {
}
@Test
void testNestedGrowingList() {
public void testNestedGrowingList() {
Form form = new Form();
DataBinder binder = new DataBinder(form, "form");
MutablePropertyValues mpv = new MutablePropertyValues();
@@ -1937,7 +1937,7 @@ class DataBinderTests {
}
@Test
void testFieldErrorAccessVariations() {
public void testFieldErrorAccessVariations() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
assertThat(binder.getBindingResult().getGlobalError()).isNull();
@@ -1958,7 +1958,7 @@ class DataBinderTests {
}
@Test // SPR-14888
void testSetAutoGrowCollectionLimit() {
public void testSetAutoGrowCollectionLimit() {
BeanWithIntegerList tb = new BeanWithIntegerList();
DataBinder binder = new DataBinder(tb);
binder.setAutoGrowCollectionLimit(257);
@@ -1968,11 +1968,11 @@ class DataBinderTests {
binder.bind(pvs);
assertThat(tb.getIntegerList().size()).isEqualTo(257);
assertThat(tb.getIntegerList().get(256)).isEqualTo(Integer.valueOf(1));
assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(Integer.valueOf(1));
}
@Test // SPR-14888
void testSetAutoGrowCollectionLimitAfterInitialization() {
public void testSetAutoGrowCollectionLimitAfterInitialization() {
DataBinder binder = new DataBinder(new BeanWithIntegerList());
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
assertThatIllegalStateException().isThrownBy(() ->
@@ -1981,7 +1981,7 @@ class DataBinderTests {
}
@Test // SPR-15009
void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() {
public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
@@ -1998,7 +1998,7 @@ class DataBinderTests {
}
@Test // SPR-15009
void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() {
public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
@@ -2013,7 +2013,7 @@ class DataBinderTests {
}
@Test // SPR-15009
void testSetCustomMessageCodesResolverAfterInitializeBindingResult() {
public void testSetCustomMessageCodesResolverAfterInitializeBindingResult() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.initBeanPropertyAccess();
@@ -2028,7 +2028,7 @@ class DataBinderTests {
}
@Test // SPR-15009
void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() {
public void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.initBeanPropertyAccess();
@@ -2042,7 +2042,7 @@ class DataBinderTests {
}
@Test // SPR-15009
void testCallSetMessageCodesResolverTwice() {
public void testCallSetMessageCodesResolverTwice() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
@@ -2053,7 +2053,7 @@ class DataBinderTests {
}
@Test // gh-24347
void overrideBindingResultType() {
public void overrideBindingResultType() {
TestBean testBean = new TestBean();
DataBinder binder = new DataBinder(testBean, "testBean");
binder.initDirectFieldAccess();
@@ -0,0 +1,35 @@
description = "Spring Core Coroutines support"
apply plugin: "kotlin"
configurations {
classesOnlyElements {
canBeConsumed = true
canBeResolved = false
}
}
artifacts {
classesOnlyElements(compileKotlin.destinationDir)
}
dependencies {
compile("org.jetbrains.kotlin:kotlin-reflect")
compile("org.jetbrains.kotlin:kotlin-stdlib")
compile("io.projectreactor:reactor-core")
compile("org.jetbrains.kotlinx:kotlinx-coroutines-core")
compile("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
}
eclipse {
project {
buildCommand "org.jetbrains.kotlin.ui.kotlinBuilder"
buildCommand "org.eclipse.jdt.core.javabuilder"
natures "org.jetbrains.kotlin.core.kotlinNature"
natures "org.eclipse.jdt.core.javanature"
linkedResource name: "kotlin_bin", type: "2", locationUri: "org.jetbrains.kotlin.core.filesystem:/" + project.name + "/kotlin_bin"
}
classpath {
containers "org.jetbrains.kotlin.core.KOTLIN_CONTAINER"
}
}
@@ -0,0 +1,71 @@
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("CoroutinesUtils")
package org.springframework.core
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.awaitSingleOrNull
import kotlinx.coroutines.reactor.asFlux
import kotlinx.coroutines.reactor.mono
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import kotlin.reflect.full.callSuspend
import kotlin.reflect.jvm.kotlinFunction
/**
* Convert a [Deferred] instance to a [Mono] one.
*
* @author Sebastien Deleuze
* @since 5.2
*/
internal fun <T: Any> deferredToMono(source: Deferred<T>) =
mono(Dispatchers.Unconfined) { source.await() }
/**
* Convert a [Mono] instance to a [Deferred] one.
*
* @author Sebastien Deleuze
* @since 5.2
*/
@Suppress("DEPRECATION")
@OptIn(DelicateCoroutinesApi::class)
internal fun <T: Any> monoToDeferred(source: Mono<T>) =
GlobalScope.async(Dispatchers.Unconfined) { source.awaitSingleOrNull() }
/**
* Invoke a suspending function and converts it to [Mono] or [reactor.core.publisher.Flux].
*
* @author Sebastien Deleuze
* @since 5.2
*/
@Suppress("UNCHECKED_CAST")
fun invokeSuspendingFunction(method: Method, target: Any, vararg args: Any?): Publisher<*> {
val function = method.kotlinFunction!!
val mono = mono(Dispatchers.Unconfined) {
function.callSuspend(target, *args.sliceArray(0..(args.size-2))).let { if (it == Unit) null else it }
}.onErrorMap(InvocationTargetException::class.java) { it.targetException }
return if (function.returnType.classifier == Flow::class) {
mono.flatMapMany { (it as Flow<Any>).asFlux() }
}
else {
mono
}
}
+21 -18
View File
@@ -13,19 +13,20 @@ def objenesisVersion = "3.2"
configurations {
cglib
objenesis
coroutines
}
task cglibRepackJar(type: ShadowJar) {
archiveBaseName.set('spring-cglib-repack')
archiveVersion.set(cglibVersion)
archiveBaseName = 'spring-cglib-repack'
archiveVersion = cglibVersion
configurations = [project.configurations.cglib]
relocate 'net.sf.cglib', 'org.springframework.cglib'
relocate 'org.objectweb.asm', 'org.springframework.asm'
}
task objenesisRepackJar(type: ShadowJar) {
archiveBaseName.set('spring-objenesis-repack')
archiveVersion.set(objenesisVersion)
archiveBaseName = 'spring-objenesis-repack'
archiveVersion = objenesisVersion
configurations = [project.configurations.objenesis]
relocate 'org.objenesis', 'org.springframework.objenesis'
}
@@ -33,31 +34,31 @@ task objenesisRepackJar(type: ShadowJar) {
dependencies {
cglib("cglib:cglib:${cglibVersion}@jar")
objenesis("org.objenesis:objenesis:${objenesisVersion}@jar")
api(files(cglibRepackJar))
api(files(objenesisRepackJar))
api(project(":spring-jcl"))
coroutines(project(path: ":kotlin-coroutines", configuration: 'classesOnlyElements'))
compile(files(cglibRepackJar))
compile(files(objenesisRepackJar))
compile(project(":spring-jcl"))
compileOnly(project(":kotlin-coroutines"))
compileOnly("io.projectreactor.tools:blockhound")
optional("net.sf.jopt-simple:jopt-simple")
optional("org.aspectj:aspectjweaver")
optional("org.jetbrains.kotlin:kotlin-reflect")
optional("org.jetbrains.kotlin:kotlin-stdlib")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-core")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
optional("io.projectreactor:reactor-core")
optional("io.reactivex:rxjava")
optional("io.reactivex:rxjava-reactive-streams")
optional("io.reactivex.rxjava2:rxjava")
optional("io.reactivex.rxjava3:rxjava")
optional("io.smallrye.reactive:mutiny")
optional("io.netty:netty-buffer")
testImplementation("io.projectreactor:reactor-test")
testImplementation("com.google.code.findbugs:jsr305")
testImplementation("javax.annotation:javax.annotation-api")
testImplementation("javax.xml.bind:jaxb-api")
testImplementation("com.fasterxml.woodstox:woodstox-core")
testImplementation("org.xmlunit:xmlunit-assertj")
testImplementation("org.xmlunit:xmlunit-matchers")
testImplementation("io.projectreactor.tools:blockhound")
testCompile("io.projectreactor:reactor-test")
testCompile("com.google.code.findbugs:jsr305")
testCompile("javax.annotation:javax.annotation-api")
testCompile("javax.xml.bind:jaxb-api")
testCompile("com.fasterxml.woodstox:woodstox-core")
testCompile("org.xmlunit:xmlunit-assertj")
testCompile("org.xmlunit:xmlunit-matchers")
testCompile(project(":kotlin-coroutines"))
testCompile("io.projectreactor.tools:blockhound")
testFixturesImplementation("io.projectreactor:reactor-test")
testFixturesImplementation("com.google.code.findbugs:jsr305")
testFixturesImplementation("org.junit.platform:junit-platform-launcher")
@@ -89,6 +90,8 @@ jar {
from(zipTree(objenesisRepackJar.archivePath)) {
include "org/springframework/objenesis/**"
}
from configurations.coroutines
}
test {
@@ -1,116 +0,0 @@
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
/**
* Benchmarks for {@link StringUtils}.
*
* @author Brian Clozel
*/
@BenchmarkMode(Mode.Throughput)
public class StringUtilsBenchmark {
@Benchmark
public void collectionToDelimitedString(DelimitedStringState state, Blackhole bh) {
bh.consume(StringUtils.collectionToCommaDelimitedString(state.elements));
}
@State(Scope.Benchmark)
public static class DelimitedStringState {
@Param("10")
int elementMinSize;
@Param("20")
int elementMaxSize;
@Param("10")
int elementCount;
Collection<String> elements;
@Setup(Level.Iteration)
public void setup() {
Random random = new Random();
this.elements = new ArrayList<>(this.elementCount);
int bound = this.elementMaxSize - this.elementMinSize;
for (int i = 0; i < this.elementCount; i++) {
this.elements.add(String.format("%0" + (random.nextInt(bound) + this.elementMinSize) + "d", 1));
}
}
}
@Benchmark
public void cleanPath(CleanPathState state, Blackhole bh) {
for (String path : state.paths) {
bh.consume(StringUtils.cleanPath(path));
}
}
@State(Scope.Benchmark)
public static class CleanPathState {
private static final List<String> SEGMENTS = Arrays.asList("some", "path", ".", "..", "springspring");
@Param("10")
int segmentCount;
@Param("20")
int pathsCount;
Collection<String> paths;
@Setup(Level.Iteration)
public void setup() {
this.paths = new ArrayList<>(this.pathsCount);
Random random = new Random();
for (int i = 0; i < this.pathsCount; i++) {
this.paths.add(createSamplePath(random));
}
}
private String createSamplePath(Random random) {
String separator = random.nextBoolean() ? "/" : "\\";
StringBuilder sb = new StringBuilder();
sb.append("jar:file:///c:");
for (int i = 0; i < this.segmentCount; i++) {
sb.append(separator);
sb.append(SEGMENTS.get(random.nextInt(SEGMENTS.size())));
}
sb.append(separator);
sb.append("the%20file.txt");
return sb.toString();
}
}
}
@@ -38,8 +38,8 @@ package org.springframework.asm;
public abstract class AnnotationVisitor {
/**
* The ASM API version implemented by this visitor. The value of this field must be one of the
* {@code ASM}<i>x</i> values in {@link Opcodes}.
* The ASM API version implemented by this visitor. The value of this field must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
protected final int api;
@@ -52,8 +52,8 @@ public abstract class AnnotationVisitor {
/**
* Constructs a new {@link AnnotationVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
public AnnotationVisitor(final int api) {
this(api, null);
@@ -62,8 +62,8 @@ public abstract class AnnotationVisitor {
/**
* Constructs a new {@link AnnotationVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
* @param annotationVisitor the annotation visitor to which this visitor must delegate method
* calls. May be {@literal null}.
*/
@@ -352,9 +352,6 @@ public class ByteVector {
* @param size number of additional bytes that this byte vector should be able to receive.
*/
private void enlarge(final int size) {
if (length > data.length) {
throw new AssertionError("Internal error");
}
int doubleCapacity = 2 * data.length;
int minimalCapacity = length + size;
byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];
@@ -40,8 +40,8 @@ package org.springframework.asm;
public abstract class ClassVisitor {
/**
* The ASM API version implemented by this visitor. The value of this field must be one of the
* {@code ASM}<i>x</i> values in {@link Opcodes}.
* The ASM API version implemented by this visitor. The value of this field must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
protected final int api;
@@ -51,8 +51,8 @@ public abstract class ClassVisitor {
/**
* Constructs a new {@link ClassVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
public ClassVisitor(final int api) {
this(api, null);
@@ -61,8 +61,9 @@ public abstract class ClassVisitor {
/**
* Constructs a new {@link ClassVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7}, {@link
* Opcodes#ASM8} or {@link Opcodes#ASM9}.
* @param classVisitor the class visitor to which this visitor must delegate method calls. May be
* null.
*/
@@ -37,8 +37,9 @@ package org.springframework.asm;
public abstract class FieldVisitor {
/**
* The ASM API version implemented by this visitor. The value of this field must be one of the
* {@code ASM}<i>x</i> values in {@link Opcodes}.
* The ASM API version implemented by this visitor. The value of this field must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7}, {@link
* Opcodes#ASM8} or {@link Opcodes#ASM9}.
*/
protected final int api;
@@ -48,8 +49,9 @@ public abstract class FieldVisitor {
/**
* Constructs a new {@link FieldVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7}, {@link
* Opcodes#ASM8} or {@link Opcodes#ASM9}.
*/
public FieldVisitor(final int api) {
this(api, null);
@@ -58,8 +60,9 @@ public abstract class FieldVisitor {
/**
* Constructs a new {@link FieldVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6}, {@link Opcodes#ASM7} or {@link
* Opcodes#ASM8}.
* @param fieldVisitor the field visitor to which this visitor must delegate method calls. May be
* null.
*/
@@ -51,8 +51,8 @@ public abstract class MethodVisitor {
private static final String REQUIRES_ASM5 = "This feature requires ASM5";
/**
* The ASM API version implemented by this visitor. The value of this field must be one of the
* {@code ASM}<i>x</i> values in {@link Opcodes}.
* The ASM API version implemented by this visitor. The value of this field must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
protected final int api;
@@ -64,8 +64,8 @@ public abstract class MethodVisitor {
/**
* Constructs a new {@link MethodVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
*/
public MethodVisitor(final int api) {
this(api, null);
@@ -74,8 +74,8 @@ public abstract class MethodVisitor {
/**
* Constructs a new {@link MethodVisitor}.
*
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
* @param api the ASM API version implemented by this visitor. Must be one of {@link
* Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}.
* @param methodVisitor the method visitor to which this visitor must delegate method calls. May
* be null.
*/
@@ -1,95 +0,0 @@
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import kotlin.Unit;
import kotlin.jvm.JvmClassMappingKt;
import kotlin.reflect.KClassifier;
import kotlin.reflect.KFunction;
import kotlin.reflect.full.KCallables;
import kotlin.reflect.jvm.ReflectJvmMapping;
import kotlinx.coroutines.BuildersKt;
import kotlinx.coroutines.CoroutineStart;
import kotlinx.coroutines.Deferred;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.GlobalScope;
import kotlinx.coroutines.flow.Flow;
import kotlinx.coroutines.reactor.MonoKt;
import kotlinx.coroutines.reactor.ReactorFlowKt;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Utilities for working with Kotlin Coroutines.
*
* @author Sebastien Deleuze
* @author Phillip Webb
* @since 5.2
*/
public abstract class CoroutinesUtils {
/**
* Convert a {@link Deferred} instance to a {@link Mono}.
*/
public static <T> Mono<T> deferredToMono(Deferred<T> source) {
return MonoKt.mono(Dispatchers.getUnconfined(),
(scope, continuation) -> source.await(continuation));
}
/**
* Convert a {@link Mono} instance to a {@link Deferred}.
*/
public static <T> Deferred<T> monoToDeferred(Mono<T> source) {
return BuildersKt.async(GlobalScope.INSTANCE, Dispatchers.getUnconfined(),
CoroutineStart.DEFAULT,
(scope, continuation) -> MonoKt.awaitSingleOrNull(source, continuation));
}
/**
* Invoke a suspending function and converts it to {@link Mono} or
* {@link Flux}.
*/
public static Publisher<?> invokeSuspendingFunction(Method method, Object target, Object... args) {
KFunction<?> function = Objects.requireNonNull(ReflectJvmMapping.getKotlinFunction(method));
KClassifier classifier = function.getReturnType().getClassifier();
Mono<Object> mono = MonoKt.mono(Dispatchers.getUnconfined(), (scope, continuation) ->
KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation))
.filter(result -> !Objects.equals(result, Unit.INSTANCE))
.onErrorMap(InvocationTargetException.class, InvocationTargetException::getTargetException);
if (classifier != null && classifier.equals(JvmClassMappingKt.getKotlinClass(Flow.class))) {
return mono.flatMapMany(CoroutinesUtils::asFlux);
}
return mono;
}
private static Object[] getSuspendedFunctionArgs(Object target, Object... args) {
Object[] functionArgs = new Object[args.length];
functionArgs[0] = target;
System.arraycopy(args, 0, functionArgs, 1, args.length - 1);
return functionArgs;
}
private static Flux<?> asFlux(Object flow) {
return ReactorFlowKt.asFlux(((Flow<?>) flow));
}
}
@@ -72,8 +72,6 @@ public class ReactiveAdapterRegistry {
private static final boolean kotlinCoroutinesPresent;
private static final boolean mutinyPresent;
static {
ClassLoader classLoader = ReactiveAdapterRegistry.class.getClassLoader();
reactorPresent = ClassUtils.isPresent("reactor.core.publisher.Flux", classLoader);
@@ -83,7 +81,6 @@ public class ReactiveAdapterRegistry {
rxjava3Present = ClassUtils.isPresent("io.reactivex.rxjava3.core.Flowable", classLoader);
flowPublisherPresent = ClassUtils.isPresent("java.util.concurrent.Flow.Publisher", classLoader);
kotlinCoroutinesPresent = ClassUtils.isPresent("kotlinx.coroutines.reactor.MonoKt", classLoader);
mutinyPresent = ClassUtils.isPresent("io.smallrye.mutiny.Multi", classLoader);
}
private final List<ReactiveAdapter> adapters = new ArrayList<>();
@@ -124,11 +121,6 @@ public class ReactiveAdapterRegistry {
if (reactorPresent && kotlinCoroutinesPresent) {
new CoroutinesRegistrar().registerAdapters(this);
}
// SmallRye Mutiny
if (mutinyPresent) {
new MutinyRegistrar().registerAdapters(this);
}
}
@@ -426,28 +418,6 @@ public class ReactiveAdapterRegistry {
}
private static class MutinyRegistrar {
void registerAdapters(ReactiveAdapterRegistry registry) {
registry.registerReactiveType(
ReactiveTypeDescriptor.singleOptionalValue(
io.smallrye.mutiny.Uni.class,
() -> io.smallrye.mutiny.Uni.createFrom().nothing()),
uni -> ((io.smallrye.mutiny.Uni<?>) uni).convert().toPublisher(),
publisher -> io.smallrye.mutiny.Uni.createFrom().publisher(publisher)
);
registry.registerReactiveType(
ReactiveTypeDescriptor.multiValue(
io.smallrye.mutiny.Multi.class,
() -> io.smallrye.mutiny.Multi.createFrom().empty()),
multi -> (io.smallrye.mutiny.Multi<?>) multi,
publisher -> io.smallrye.mutiny.Multi.createFrom().publisher(publisher)
);
}
}
/**
* {@code BlockHoundIntegration} for spring-core classes.
* <p>Explicitly allow the following:
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -174,7 +174,7 @@ public class ConcurrentLruCache<K, V> {
}
/**
* Return the maximum number of entries in the cache
* Return the the maximum number of entries in the cache
* (0 indicates no caching, always generating a new value).
* @see #size()
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 abstract class ObjectUtils {
* Determine whether the given object is empty.
* <p>This method supports the following object types.
* <ul>
* <li>{@code Optional}: considered empty if not {@link Optional#isPresent()}</li>
* <li>{@code Optional}: considered empty if {@link Optional#empty()}</li>
* <li>{@code Array}: considered empty if its length is zero</li>
* <li>{@link CharSequence}: considered empty if its length is zero</li>
* <li>{@link Collection}: delegates to {@link Collection#isEmpty()}</li>
@@ -667,9 +667,7 @@ public abstract class StringUtils {
if (!hasLength(path)) {
return path;
}
String normalizedPath = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
String pathToUse = normalizedPath;
String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
// Shortcut if there is no work to do
if (pathToUse.indexOf('.') == -1) {
@@ -697,8 +695,7 @@ public abstract class StringUtils {
}
String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);
// we never require more elements than pathArray and in the common case the same number
Deque<String> pathElements = new ArrayDeque<>(pathArray.length);
Deque<String> pathElements = new ArrayDeque<>();
int tops = 0;
for (int i = pathArray.length - 1; i >= 0; i--) {
@@ -724,7 +721,7 @@ public abstract class StringUtils {
// All path elements stayed the same - shortcut
if (pathArray.length == pathElements.size()) {
return normalizedPath;
return prefix + pathToUse;
}
// Remaining top paths need to be retained.
for (int i = 0; i < tops; i++) {
@@ -735,9 +732,7 @@ public abstract class StringUtils {
pathElements.addFirst(CURRENT_PATH);
}
final String joined = collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
// avoid string concatenation with empty prefix
return prefix.isEmpty() ? joined : prefix + joined;
return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
}
/**
@@ -1299,12 +1294,7 @@ public abstract class StringUtils {
return "";
}
int totalLength = coll.size() * (prefix.length() + suffix.length()) + (coll.size() - 1) * delim.length();
for (Object element : coll) {
totalLength += element.toString().length();
}
StringBuilder sb = new StringBuilder(totalLength);
StringBuilder sb = new StringBuilder();
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
@@ -21,8 +21,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import kotlinx.coroutines.Deferred;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -40,9 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("unchecked")
class ReactiveAdapterRegistryTests {
private static final Duration ONE_SECOND = Duration.ofSeconds(1);
private final ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
@@ -88,7 +83,7 @@ class ReactiveAdapterRegistryTests {
Publisher<Integer> source = io.reactivex.rxjava3.core.Flowable.fromIterable(sequence);
Object target = getAdapter(Flux.class).fromPublisher(source);
assertThat(target instanceof Flux).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -96,7 +91,7 @@ class ReactiveAdapterRegistryTests {
Publisher<Integer> source = io.reactivex.rxjava3.core.Flowable.fromArray(1, 2, 3);
Object target = getAdapter(Mono.class).fromPublisher(source);
assertThat(target instanceof Mono).isTrue();
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
@@ -113,7 +108,7 @@ class ReactiveAdapterRegistryTests {
future.complete(1);
Object target = getAdapter(CompletableFuture.class).toPublisher(future);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
}
@@ -158,7 +153,7 @@ class ReactiveAdapterRegistryTests {
Object source = rx.Observable.from(sequence);
Object target = getAdapter(rx.Observable.class).toPublisher(source);
assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -166,7 +161,7 @@ class ReactiveAdapterRegistryTests {
Object source = rx.Single.just(1);
Object target = getAdapter(rx.Single.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
@@ -174,7 +169,7 @@ class ReactiveAdapterRegistryTests {
Object source = rx.Completable.complete();
Object target = getAdapter(rx.Completable.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
((Mono<Void>) target).block(ONE_SECOND);
((Mono<Void>) target).block(Duration.ofMillis(1000));
}
}
@@ -232,7 +227,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.Flowable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Flowable.class).toPublisher(source);
assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -241,7 +236,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.Observable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.Observable.class).toPublisher(source);
assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -249,7 +244,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.Single.just(1);
Object target = getAdapter(io.reactivex.Single.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
@@ -257,7 +252,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.Completable.complete();
Object target = getAdapter(io.reactivex.Completable.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
((Mono<Void>) target).block(ONE_SECOND);
((Mono<Void>) target).block(Duration.ofMillis(1000));
}
}
@@ -315,7 +310,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.rxjava3.core.Flowable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.rxjava3.core.Flowable.class).toPublisher(source);
assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -324,7 +319,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.rxjava3.core.Observable.fromIterable(sequence);
Object target = getAdapter(io.reactivex.rxjava3.core.Observable.class).toPublisher(source);
assertThat(target instanceof Flux).as("Expected Flux Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Flux<Integer>) target).collectList().block(ONE_SECOND)).isEqualTo(sequence);
assertThat(((Flux<Integer>) target).collectList().block(Duration.ofMillis(1000))).isEqualTo(sequence);
}
@Test
@@ -332,7 +327,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.rxjava3.core.Single.just(1);
Object target = getAdapter(io.reactivex.rxjava3.core.Single.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
assertThat(((Mono<Integer>) target).block(Duration.ofMillis(1000))).isEqualTo(Integer.valueOf(1));
}
@Test
@@ -340,7 +335,7 @@ class ReactiveAdapterRegistryTests {
Object source = io.reactivex.rxjava3.core.Completable.complete();
Object target = getAdapter(io.reactivex.rxjava3.core.Completable.class).toPublisher(source);
assertThat(target instanceof Mono).as("Expected Mono Publisher: " + target.getClass().getName()).isTrue();
((Mono<Void>) target).block(ONE_SECOND);
((Mono<Void>) target).block(Duration.ofMillis(1000));
}
}
@@ -362,51 +357,6 @@ class ReactiveAdapterRegistryTests {
}
}
@Nested
class Mutiny {
@Test
void defaultAdapterRegistrations() {
assertThat(getAdapter(io.smallrye.mutiny.Uni.class)).isNotNull();
assertThat(getAdapter(io.smallrye.mutiny.Multi.class)).isNotNull();
}
@Test
void toUni() {
Publisher<Integer> source = Mono.just(1);
Object target = getAdapter(Uni.class).fromPublisher(source);
assertThat(target).isInstanceOf(Uni.class);
assertThat(((Uni<Integer>) target).await().atMost(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
}
@Test
void fromUni() {
Uni<Integer> source = Uni.createFrom().item(1);
Object target = getAdapter(Uni.class).toPublisher(source);
assertThat(target).isInstanceOf(Mono.class);
assertThat(((Mono<Integer>) target).block(ONE_SECOND)).isEqualTo(Integer.valueOf(1));
}
@Test
void toMulti() {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Publisher<Integer> source = Flux.fromIterable(sequence);
Object target = getAdapter(Multi.class).fromPublisher(source);
assertThat(target).isInstanceOf(Multi.class);
assertThat(((Multi<Integer>) target).collect().asList().await().atMost(ONE_SECOND)).isEqualTo(sequence);
}
@Test
void fromMulti() {
List<Integer> sequence = Arrays.asList(1, 2, 3);
Multi<Integer> source = Multi.createFrom().iterable(sequence);
Object target = getAdapter(Multi.class).toPublisher(source);
assertThat(target).isInstanceOf(Flux.class);
assertThat(((Flux<Integer>) target).blockLast(ONE_SECOND)).isEqualTo(Integer.valueOf(3));
}
}
private ReactiveAdapter getAdapter(Class<?> reactiveType) {
ReactiveAdapter adapter = this.registry.getAdapter(reactiveType);
assertThat(adapter).isNotNull();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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.util;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -108,7 +109,7 @@ class ObjectUtilsTests {
Set<String> set = new HashSet<>();
set.add("foo");
assertThat(isEmpty(set)).isFalse();
assertThat(isEmpty(Collections.singletonList("foo"))).isFalse();
assertThat(isEmpty(Arrays.asList("foo"))).isFalse();
}
@Test
@@ -158,7 +159,7 @@ class ObjectUtilsTests {
void toObjectArrayWithEmptyPrimitiveArray() {
Object[] objects = ObjectUtils.toObjectArray(new byte[] {});
assertThat(objects).isNotNull();
assertThat(objects).hasSize(0);
assertThat(objects.length).isEqualTo(0);
}
@Test
@@ -178,7 +179,7 @@ class ObjectUtilsTests {
String[] array = new String[] {"foo", "bar"};
String newElement = "baz";
Object[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertThat(newArray).hasSize(3);
assertThat(newArray.length).isEqualTo(3);
assertThat(newArray[2]).isEqualTo(newElement);
}
@@ -187,7 +188,7 @@ class ObjectUtilsTests {
String[] array = new String[0];
String newElement = "foo";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertThat(newArray).hasSize(1);
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(newElement);
}
@@ -197,7 +198,7 @@ class ObjectUtilsTests {
String[] array = new String[] {existingElement};
String newElement = "bar";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertThat(newArray).hasSize(2);
assertThat(newArray.length).isEqualTo(2);
assertThat(newArray[0]).isEqualTo(existingElement);
assertThat(newArray[1]).isEqualTo(newElement);
}
@@ -207,8 +208,8 @@ class ObjectUtilsTests {
String[] array = new String[] {null};
String newElement = "bar";
String[] newArray = ObjectUtils.addObjectToArray(array, newElement);
assertThat(newArray).hasSize(2);
assertThat(newArray[0]).isNull();
assertThat(newArray.length).isEqualTo(2);
assertThat(newArray[0]).isEqualTo(null);
assertThat(newArray[1]).isEqualTo(newElement);
}
@@ -216,15 +217,15 @@ class ObjectUtilsTests {
void addObjectToNullArray() throws Exception {
String newElement = "foo";
String[] newArray = ObjectUtils.addObjectToArray(null, newElement);
assertThat(newArray).hasSize(1);
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(newElement);
}
@Test
void addNullObjectToNullArray() throws Exception {
Object[] newArray = ObjectUtils.addObjectToArray(null, null);
assertThat(newArray).hasSize(1);
assertThat(newArray[0]).isNull();
assertThat(newArray.length).isEqualTo(1);
assertThat(newArray[0]).isEqualTo(null);
}
@Test
@@ -259,7 +260,7 @@ class ObjectUtilsTests {
@Deprecated
void hashCodeWithFloat() {
float flt = 34.8f;
int expected = (Float.valueOf(flt)).hashCode();
int expected = (new Float(flt)).hashCode();
assertThat(ObjectUtils.hashCode(flt)).isEqualTo(expected);
}
@@ -267,7 +268,7 @@ class ObjectUtilsTests {
@Deprecated
void hashCodeWithLong() {
long lng = 883L;
int expected = (Long.valueOf(lng)).hashCode();
int expected = (new Long(lng)).hashCode();
assertThat(ObjectUtils.hashCode(lng)).isEqualTo(expected);
}
@@ -281,7 +282,7 @@ class ObjectUtilsTests {
@Test
void identityToStringWithNullObject() {
assertThat(ObjectUtils.identityToString(null)).isEmpty();
assertThat(ObjectUtils.identityToString(null)).isEqualTo("");
}
@Test
@@ -402,8 +402,6 @@ class StringUtilsTests {
assertThat(StringUtils.cleanPath("file:.././")).isEqualTo("file:../");
assertThat(StringUtils.cleanPath("file:/mypath/spring.factories")).isEqualTo("file:/mypath/spring.factories");
assertThat(StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")).isEqualTo("file:///c:/path/the%20file.txt");
assertThat(StringUtils.cleanPath("jar:file:///c:\\some\\..\\path\\.\\the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt");
assertThat(StringUtils.cleanPath("jar:file:///c:/some/../path/./the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt");
}
@Test
@@ -0,0 +1,46 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.testfixture;
import org.apache.commons.logging.Log;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
/**
* Utility methods that allow JUnit tests to assume certain conditions hold
* {@code true}. If an assumption fails, it means the test should be aborted.
*
* @author Rob Winch
* @author Phillip Webb
* @author Sam Brannen
* @since 3.2
* @see #notLogging(Log)
* @see EnabledForTestGroups @EnabledForTestGroups
*/
public abstract class Assume {
/**
* Assume that the specified log is not set to Trace or Debug.
* @param log the log to test
* @throws org.opentest4j.TestAbortedException if the assumption fails
*/
public static void notLogging(Log log) {
assumeFalse(log.isTraceEnabled());
assumeFalse(log.isDebugEnabled());
}
}
+4 -4
View File
@@ -3,8 +3,8 @@ description = "Spring Expression Language (SpEL)"
apply plugin: "kotlin"
dependencies {
api(project(":spring-core"))
testImplementation(testFixtures(project(":spring-core")))
testImplementation("org.jetbrains.kotlin:kotlin-reflect")
testImplementation("org.jetbrains.kotlin:kotlin-stdlib")
compile(project(":spring-core"))
testCompile(testFixtures(project(":spring-core")))
testCompile("org.jetbrains.kotlin:kotlin-reflect")
testCompile("org.jetbrains.kotlin:kotlin-stdlib")
}
@@ -57,7 +57,7 @@ import org.springframework.util.Assert;
*/
public class ConstructorReference extends SpelNodeImpl {
private final boolean isArrayConstructor;
private boolean isArrayConstructor = false;
@Nullable
private SpelNodeImpl[] dimensions;
@@ -234,7 +234,6 @@ public class ConstructorReference extends SpelNodeImpl {
FormatHelper.formatClassNameForMessage(
intendedArrayType != null ? intendedArrayType.getClass() : null));
}
String type = (String) intendedArrayType;
Class<?> componentType;
TypeCode arrayTypeCode = TypeCode.forName(type);
@@ -244,8 +243,7 @@ public class ConstructorReference extends SpelNodeImpl {
else {
componentType = arrayTypeCode.getType();
}
Object newArray = null;
Object newArray;
if (!hasInitializer()) {
// Confirm all dimensions were specified (for example [3][][5] is missing the 2nd dimension)
if (this.dimensions != null) {
@@ -254,22 +252,23 @@ public class ConstructorReference extends SpelNodeImpl {
throw new SpelEvaluationException(getStartPosition(), SpelMessage.MISSING_ARRAY_DIMENSION);
}
}
TypeConverter typeConverter = state.getEvaluationContext().getTypeConverter();
if (this.dimensions.length == 1) {
// Shortcut for 1-dimensional
TypedValue o = this.dimensions[0].getTypedValue(state);
int arraySize = ExpressionUtils.toInt(typeConverter, o);
newArray = Array.newInstance(componentType, arraySize);
}
else {
// Multi-dimensional - hold onto your hat!
int[] dims = new int[this.dimensions.length];
for (int d = 0; d < this.dimensions.length; d++) {
TypedValue o = this.dimensions[d].getTypedValue(state);
dims[d] = ExpressionUtils.toInt(typeConverter, o);
}
newArray = Array.newInstance(componentType, dims);
}
TypeConverter typeConverter = state.getEvaluationContext().getTypeConverter();
// Shortcut for 1 dimensional
if (this.dimensions.length == 1) {
TypedValue o = this.dimensions[0].getTypedValue(state);
int arraySize = ExpressionUtils.toInt(typeConverter, o);
newArray = Array.newInstance(componentType, arraySize);
}
else {
// Multi-dimensional - hold onto your hat!
int[] dims = new int[this.dimensions.length];
for (int d = 0; d < this.dimensions.length; d++) {
TypedValue o = this.dimensions[d].getTypedValue(state);
dims[d] = ExpressionUtils.toInt(typeConverter, o);
}
newArray = Array.newInstance(componentType, dims);
}
}
else {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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,11 +41,11 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("rawtypes")
class IndexingTests {
public class IndexingTests {
@Test
@SuppressWarnings("unchecked")
void indexIntoGenericPropertyContainingMap() {
public void indexIntoGenericPropertyContainingMap() {
Map<String, String> property = new HashMap<>();
property.put("foo", "bar");
this.property = property;
@@ -63,7 +63,7 @@ class IndexingTests {
@Test
@SuppressWarnings("unchecked")
void indexIntoGenericPropertyContainingMapObject() {
public void indexIntoGenericPropertyContainingMapObject() {
Map<String, Map<String, String>> property = new HashMap<>();
Map<String, String> map = new HashMap<>();
map.put("foo", "bar");
@@ -112,7 +112,7 @@ class IndexingTests {
}
@Test
void setGenericPropertyContainingMap() {
public void setGenericPropertyContainingMap() {
Map<String, String> property = new HashMap<>();
property.put("foo", "bar");
this.property = property;
@@ -127,7 +127,7 @@ class IndexingTests {
}
@Test
void setPropertyContainingMap() {
public void setPropertyContainingMap() {
Map<Integer, Integer> property = new HashMap<>();
property.put(9, 3);
this.parameterizedMap = property;
@@ -144,7 +144,7 @@ class IndexingTests {
public Map<Integer, Integer> parameterizedMap;
@Test
void setPropertyContainingMapAutoGrow() {
public void setPropertyContainingMapAutoGrow() {
SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, false));
Expression expression = parser.parseExpression("parameterizedMap");
assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.Map<java.lang.Integer, java.lang.Integer>");
@@ -156,7 +156,7 @@ class IndexingTests {
}
@Test
void indexIntoGenericPropertyContainingList() {
public void indexIntoGenericPropertyContainingList() {
List<String> property = new ArrayList<>();
property.add("bar");
this.property = property;
@@ -169,7 +169,7 @@ class IndexingTests {
}
@Test
void setGenericPropertyContainingList() {
public void setGenericPropertyContainingList() {
List<Integer> property = new ArrayList<>();
property.add(3);
this.property = property;
@@ -184,7 +184,7 @@ class IndexingTests {
}
@Test
void setGenericPropertyContainingListAutogrow() {
public void setGenericPropertyContainingListAutogrow() {
List<Integer> property = new ArrayList<>();
this.property = property;
SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
@@ -203,7 +203,7 @@ class IndexingTests {
public List<BigDecimal> decimals;
@Test
void autoGrowListOfElementsWithoutDefaultConstructor() {
public void autoGrowListOfElementsWithoutDefaultConstructor() {
this.decimals = new ArrayList<>();
SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
parser.parseExpression("decimals[0]").setValue(this, "123.4");
@@ -211,7 +211,7 @@ class IndexingTests {
}
@Test
void indexIntoPropertyContainingListContainingNullElement() {
public void indexIntoPropertyContainingListContainingNullElement() {
this.decimals = new ArrayList<>();
this.decimals.add(null);
this.decimals.add(BigDecimal.ONE);
@@ -221,7 +221,7 @@ class IndexingTests {
}
@Test
void indexIntoPropertyContainingList() {
public void indexIntoPropertyContainingList() {
List<Integer> property = new ArrayList<>();
property.add(3);
this.parameterizedList = property;
@@ -236,7 +236,7 @@ class IndexingTests {
public List<Integer> parameterizedList;
@Test
void indexIntoPropertyContainingListOfList() {
public void indexIntoPropertyContainingListOfList() {
List<List<Integer>> property = new ArrayList<>();
property.add(Arrays.asList(3));
this.parameterizedListOfList = property;
@@ -251,7 +251,7 @@ class IndexingTests {
public List<List<Integer>> parameterizedListOfList;
@Test
void setPropertyContainingList() {
public void setPropertyContainingList() {
List<Integer> property = new ArrayList<>();
property.add(3);
this.parameterizedList = property;
@@ -266,7 +266,7 @@ class IndexingTests {
}
@Test
void indexIntoGenericPropertyContainingNullList() {
public void indexIntoGenericPropertyContainingNullList() {
SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
SpelExpressionParser parser = new SpelExpressionParser(configuration);
Expression expression = parser.parseExpression("property");
@@ -282,7 +282,7 @@ class IndexingTests {
}
@Test
void indexIntoGenericPropertyContainingGrowingList() {
public void indexIntoGenericPropertyContainingGrowingList() {
List<String> property = new ArrayList<>();
this.property = property;
SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
@@ -300,7 +300,7 @@ class IndexingTests {
}
@Test
void indexIntoGenericPropertyContainingGrowingList2() {
public void indexIntoGenericPropertyContainingGrowingList2() {
List<String> property2 = new ArrayList<>();
this.property2 = property2;
SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
@@ -320,7 +320,7 @@ class IndexingTests {
public List property2;
@Test
void indexIntoGenericPropertyContainingArray() {
public void indexIntoGenericPropertyContainingArray() {
String[] property = new String[] { "bar" };
this.property = property;
SpelExpressionParser parser = new SpelExpressionParser();
@@ -332,7 +332,7 @@ class IndexingTests {
}
@Test
void emptyList() {
public void emptyList() {
listOfScalarNotGeneric = new ArrayList();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("listOfScalarNotGeneric");
@@ -342,7 +342,7 @@ class IndexingTests {
@SuppressWarnings("unchecked")
@Test
void resolveCollectionElementType() {
public void resolveCollectionElementType() {
listNotGeneric = new ArrayList(2);
listNotGeneric.add(5);
listNotGeneric.add(6);
@@ -353,7 +353,7 @@ class IndexingTests {
}
@Test
void resolveCollectionElementTypeNull() {
public void resolveCollectionElementTypeNull() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("listNotGeneric");
assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.List<?>");
@@ -370,7 +370,7 @@ class IndexingTests {
@SuppressWarnings("unchecked")
@Test
void resolveMapKeyValueTypes() {
public void resolveMapKeyValueTypes() {
mapNotGeneric = new HashMap();
mapNotGeneric.put("baseAmount", 3.11);
mapNotGeneric.put("bonusAmount", 7.17);
@@ -384,12 +384,12 @@ class IndexingTests {
@SuppressWarnings("unchecked")
@Test
void testListOfScalar() {
public void testListOfScalar() {
listOfScalarNotGeneric = new ArrayList(1);
listOfScalarNotGeneric.add("5");
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("listOfScalarNotGeneric[0]");
assertThat(expression.getValue(this, Integer.class)).isEqualTo(Integer.valueOf(5));
assertThat(expression.getValue(this, Integer.class)).isEqualTo(new Integer(5));
}
public List listOfScalarNotGeneric;
@@ -397,7 +397,7 @@ class IndexingTests {
@SuppressWarnings("unchecked")
@Test
void testListsOfMap() {
public void testListsOfMap() {
listOfMapsNotGeneric = new ArrayList();
Map map = new HashMap();
map.put("fruit", "apple");
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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 static org.assertj.core.api.Assertions.assertThat;
* @author Juergen Hoeller
* @author Giovanni Dall'Oglio Risso
*/
class OperatorTests extends AbstractExpressionTests {
public class OperatorTests extends AbstractExpressionTests {
@Test
void testEqual() {
public void testEqual() {
evaluate("3 == 5", false, Boolean.class);
evaluate("5 == 3", false, Boolean.class);
evaluate("6 == 6", true, Boolean.class);
@@ -85,7 +85,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testNotEqual() {
public void testNotEqual() {
evaluate("3 != 5", true, Boolean.class);
evaluate("5 != 3", true, Boolean.class);
evaluate("6 != 6", false, Boolean.class);
@@ -134,7 +134,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testLessThan() {
public void testLessThan() {
evaluate("5 < 5", false, Boolean.class);
evaluate("3 < 5", true, Boolean.class);
evaluate("5 < 3", false, Boolean.class);
@@ -176,7 +176,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testLessThanOrEqual() {
public void testLessThanOrEqual() {
evaluate("3 <= 5", true, Boolean.class);
evaluate("5 <= 3", false, Boolean.class);
evaluate("6 <= 6", true, Boolean.class);
@@ -225,7 +225,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testGreaterThan() {
public void testGreaterThan() {
evaluate("3 > 5", false, Boolean.class);
evaluate("5 > 3", true, Boolean.class);
evaluate("3L > 5L", false, Boolean.class);
@@ -266,7 +266,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testGreaterThanOrEqual() {
public void testGreaterThanOrEqual() {
evaluate("3 >= 5", false, Boolean.class);
evaluate("5 >= 3", true, Boolean.class);
evaluate("6 >= 6", true, Boolean.class);
@@ -315,27 +315,27 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testIntegerLiteral() {
public void testIntegerLiteral() {
evaluate("3", 3, Integer.class);
}
@Test
void testRealLiteral() {
public void testRealLiteral() {
evaluate("3.5", 3.5d, Double.class);
}
@Test
void testMultiplyStringInt() {
public void testMultiplyStringInt() {
evaluate("'a' * 5", "aaaaa", String.class);
}
@Test
void testMultiplyDoubleDoubleGivesDouble() {
public void testMultiplyDoubleDoubleGivesDouble() {
evaluate("3.0d * 5.0d", 15.0d, Double.class);
}
@Test
void testMixedOperandsBigDecimal() {
public void testMixedOperandsBigDecimal() {
evaluate("3 * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class);
evaluate("3L * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class);
evaluate("3.0d * new java.math.BigDecimal('5')", new BigDecimal("15.0"), BigDecimal.class);
@@ -361,19 +361,19 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testMathOperatorAdd02() {
public void testMathOperatorAdd02() {
evaluate("'hello' + ' ' + 'world'", "hello world", String.class);
}
@Test
void testMathOperatorsInChains() {
public void testMathOperatorsInChains() {
evaluate("1+2+3",6,Integer.class);
evaluate("2*3*4",24,Integer.class);
evaluate("12-1-2",9,Integer.class);
}
@Test
void testIntegerArithmetic() {
public void testIntegerArithmetic() {
evaluate("2 + 4", "6", Integer.class);
evaluate("5 - 4", "1", Integer.class);
evaluate("3 * 5", 15, Integer.class);
@@ -388,7 +388,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testPlus() {
public void testPlus() throws Exception {
evaluate("7 + 2", "9", Integer.class);
evaluate("3.0f + 5.0f", 8.0f, Float.class);
evaluate("3.0d + 5.0d", 8.0d, Double.class);
@@ -419,7 +419,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testMinus() {
public void testMinus() throws Exception {
evaluate("'c' - 2", "a", String.class);
evaluate("3.0f - 5.0f", -2.0f, Float.class);
evaluateAndCheckError("'ab' - 2", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
@@ -437,7 +437,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testModulus() {
public void testModulus() {
evaluate("3%2",1,Integer.class);
evaluate("3L%2L",1L,Long.class);
evaluate("3.0f%2.0f",1f,Float.class);
@@ -448,7 +448,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testDivide() {
public void testDivide() {
evaluate("3.0f / 5.0f", 0.6f, Float.class);
evaluate("4L/2L",2L,Long.class);
evaluate("3.0f div 5.0f", 0.6f, Float.class);
@@ -461,17 +461,17 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testMathOperatorDivide_ConvertToDouble() {
evaluateAndAskForReturnType("8/4", 2.0, Double.class);
public void testMathOperatorDivide_ConvertToDouble() {
evaluateAndAskForReturnType("8/4", new Double(2.0), Double.class);
}
@Test
void testMathOperatorDivide04_ConvertToFloat() {
evaluateAndAskForReturnType("8/4", 2.0F, Float.class);
public void testMathOperatorDivide04_ConvertToFloat() {
evaluateAndAskForReturnType("8/4", new Float(2.0), Float.class);
}
@Test
void testDoubles() {
public void testDoubles() {
evaluate("3.0d == 5.0d", false, Boolean.class);
evaluate("3.0d == 3.0d", true, Boolean.class);
evaluate("3.0d != 5.0d", true, Boolean.class);
@@ -484,7 +484,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testBigDecimals() {
public void testBigDecimals() {
evaluate("3 + new java.math.BigDecimal('5')", new BigDecimal("8"), BigDecimal.class);
evaluate("3 - new java.math.BigDecimal('5')", new BigDecimal("-2"), BigDecimal.class);
evaluate("3 * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class);
@@ -495,7 +495,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testOperatorNames() {
public void testOperatorNames() throws Exception {
Operator node = getOperatorNode((SpelExpression)parser.parseExpression("1==3"));
assertThat(node.getOperatorName()).isEqualTo("==");
@@ -534,13 +534,13 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testOperatorOverloading() {
public void testOperatorOverloading() {
evaluateAndCheckError("'a' * '2'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
evaluateAndCheckError("'a' ^ '2'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
}
@Test
void testPower() {
public void testPower() {
evaluate("3^2",9,Integer.class);
evaluate("3.0d^2.0d",9.0d,Double.class);
evaluate("3L^2L",9L,Long.class);
@@ -549,7 +549,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testMixedOperands_FloatsAndDoubles() {
public void testMixedOperands_FloatsAndDoubles() {
evaluate("3.0d + 5.0f", 8.0d, Double.class);
evaluate("3.0D - 5.0f", -2.0d, Double.class);
evaluate("3.0f * 5.0d", 15.0d, Double.class);
@@ -558,7 +558,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testMixedOperands_DoublesAndInts() {
public void testMixedOperands_DoublesAndInts() {
evaluate("3.0d + 5", 8.0d, Double.class);
evaluate("3.0D - 5", -2.0d, Double.class);
evaluate("3.0f * 5", 15.0f, Float.class);
@@ -569,7 +569,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testStrings() {
public void testStrings() {
evaluate("'abc' == 'abc'", true, Boolean.class);
evaluate("'abc' == 'def'", false, Boolean.class);
evaluate("'abc' != 'abc'", false, Boolean.class);
@@ -577,7 +577,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testLongs() {
public void testLongs() {
evaluate("3L == 4L", false, Boolean.class);
evaluate("3L == 3L", true, Boolean.class);
evaluate("3L != 4L", true, Boolean.class);
@@ -588,7 +588,7 @@ class OperatorTests extends AbstractExpressionTests {
}
@Test
void testBigIntegers() {
public void testBigIntegers() {
evaluate("3 + new java.math.BigInteger('5')", new BigInteger("8"), BigInteger.class);
evaluate("3 - new java.math.BigInteger('5')", new BigInteger("-2"), BigInteger.class);
evaluate("3 * new java.math.BigInteger('5')", new BigInteger("15"), BigInteger.class);
@@ -128,7 +128,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
@Test
void typeReference() {
public void typeReference() throws Exception {
expression = parse("T(String)");
assertThat(expression.getValue()).isEqualTo(String.class);
assertCanCompile(expression);
@@ -196,7 +196,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
@SuppressWarnings("unchecked")
@Test
void operatorInstanceOf() {
public void operatorInstanceOf() throws Exception {
expression = parse("'xyz' instanceof T(String)");
assertThat(expression.getValue()).isEqualTo(true);
assertCanCompile(expression);
@@ -245,7 +245,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void operatorInstanceOf_SPR14250() throws Exception {
public void operatorInstanceOf_SPR14250() throws Exception {
// primitive left operand - should get boxed, return true
expression = parse("3 instanceof T(Integer)");
assertThat(expression.getValue()).isEqualTo(true);
@@ -292,7 +292,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void stringLiteral() throws Exception {
public void stringLiteral() throws Exception {
expression = parser.parseExpression("'abcde'");
assertThat(expression.getValue(new TestClass1(), String.class)).isEqualTo("abcde");
assertCanCompile(expression);
@@ -307,18 +307,18 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void nullLiteral() throws Exception {
public void nullLiteral() throws Exception {
expression = parser.parseExpression("null");
Object resultI = expression.getValue(new TestClass1(), Object.class);
assertCanCompile(expression);
Object resultC = expression.getValue(new TestClass1(), Object.class);
assertThat(resultI).isNull();
assertThat(resultC).isNull();
assertThat(resultC).isNull();
assertThat(resultI).isEqualTo(null);
assertThat(resultC).isEqualTo(null);
assertThat(resultC).isEqualTo(null);
}
@Test
void realLiteral() throws Exception {
public void realLiteral() throws Exception {
expression = parser.parseExpression("3.4d");
double resultI = expression.getValue(new TestClass1(), Double.TYPE);
assertCanCompile(expression);
@@ -332,7 +332,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
@SuppressWarnings("rawtypes")
@Test
void inlineList() throws Exception {
public void inlineList() throws Exception {
expression = parser.parseExpression("'abcde'.substring({1,3,4}[0])");
Object o = expression.getValue();
assertThat(o).isEqualTo("bcde");
@@ -371,7 +371,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
@SuppressWarnings("rawtypes")
@Test
void nestedInlineLists() throws Exception {
public void nestedInlineLists() throws Exception {
Object o = null;
expression = parser.parseExpression("{{1,2,3},{4,5,6},{7,8,9}}");
@@ -446,7 +446,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void intLiteral() throws Exception {
public void intLiteral() throws Exception {
expression = parser.parseExpression("42");
int resultI = expression.getValue(new TestClass1(), Integer.TYPE);
assertCanCompile(expression);
@@ -477,7 +477,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void longLiteral() throws Exception {
public void longLiteral() throws Exception {
expression = parser.parseExpression("99L");
long resultI = expression.getValue(new TestClass1(), Long.TYPE);
assertCanCompile(expression);
@@ -487,24 +487,24 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void booleanLiteral() throws Exception {
public void booleanLiteral() throws Exception {
expression = parser.parseExpression("true");
boolean resultI = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(SpelCompiler.compile(expression)).isTrue();
boolean resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultC).isTrue();
assertThat(resultC).isEqualTo(true);
expression = parser.parseExpression("false");
resultI = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isFalse();
assertThat(resultI).isEqualTo(false);
assertThat(SpelCompiler.compile(expression)).isTrue();
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultC).isFalse();
assertThat(resultC).isEqualTo(false);
}
@Test
void floatLiteral() throws Exception {
public void floatLiteral() throws Exception {
expression = parser.parseExpression("3.4f");
float resultI = expression.getValue(new TestClass1(), Float.TYPE);
assertCanCompile(expression);
@@ -517,42 +517,42 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void opOr() throws Exception {
public void opOr() throws Exception {
Expression expression = parser.parseExpression("false or false");
boolean resultI = expression.getValue(1, Boolean.TYPE);
SpelCompiler.compile(expression);
boolean resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isFalse();
assertThat(resultC).isFalse();
assertThat(resultI).isEqualTo(false);
assertThat(resultC).isEqualTo(false);
expression = parser.parseExpression("false or true");
resultI = expression.getValue(1, Boolean.TYPE);
assertCanCompile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultC).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(resultC).isEqualTo(true);
expression = parser.parseExpression("true or false");
resultI = expression.getValue(1, Boolean.TYPE);
assertCanCompile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultC).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(resultC).isEqualTo(true);
expression = parser.parseExpression("true or true");
resultI = expression.getValue(1, Boolean.TYPE);
assertCanCompile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultC).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(resultC).isEqualTo(true);
TestClass4 tc = new TestClass4();
expression = parser.parseExpression("getfalse() or gettrue()");
resultI = expression.getValue(tc, Boolean.TYPE);
assertCanCompile(expression);
resultC = expression.getValue(tc, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultC).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(resultC).isEqualTo(true);
// Can't compile this as we aren't going down the getfalse() branch in our evaluation
expression = parser.parseExpression("gettrue() or getfalse()");
@@ -584,29 +584,29 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
boolean resultI = expression.getValue(1, Boolean.TYPE);
SpelCompiler.compile(expression);
boolean resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isFalse();
assertThat(resultC).isFalse();
assertThat(resultI).isEqualTo(false);
assertThat(resultC).isEqualTo(false);
expression = parser.parseExpression("false and true");
resultI = expression.getValue(1, Boolean.TYPE);
SpelCompiler.compile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isFalse();
assertThat(resultC).isFalse();
assertThat(resultI).isEqualTo(false);
assertThat(resultC).isEqualTo(false);
expression = parser.parseExpression("true and false");
resultI = expression.getValue(1, Boolean.TYPE);
SpelCompiler.compile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isFalse();
assertThat(resultC).isFalse();
assertThat(resultI).isEqualTo(false);
assertThat(resultC).isEqualTo(false);
expression = parser.parseExpression("true and true");
resultI = expression.getValue(1, Boolean.TYPE);
SpelCompiler.compile(expression);
resultC = expression.getValue(1, Boolean.TYPE);
assertThat(resultI).isTrue();
assertThat(resultC).isTrue();
assertThat(resultI).isEqualTo(true);
assertThat(resultC).isEqualTo(true);
TestClass4 tc = new TestClass4();
@@ -3481,7 +3481,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
assertThat(tc8.s).isEqualTo("123");
assertThat(tc8.d).isCloseTo(4.0d, within(0.5d));
assertThat(tc8.z).isTrue();
assertThat(tc8.z).isEqualTo(true);
// no-arg ctor
expression = parser.parseExpression("new " + testclass8 + "()");
@@ -3507,7 +3507,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReferenceReflectiveMethodSelectionWithVarargs() throws Exception {
public void methodReferenceReflectiveMethodSelectionWithVarargs() throws Exception {
TestClass10 tc = new TestClass10();
// Should call the non varargs version of concat
@@ -3526,11 +3526,11 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
expression = parser.parseExpression("concat()");
assertCantCompile(expression);
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
assertCanCompile(expression);
tc.reset();
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
tc.reset();
// Should call the non varargs version of concat
@@ -3549,27 +3549,27 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
expression = parser.parseExpression("concat2()");
assertCantCompile(expression);
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
assertCanCompile(expression);
tc.reset();
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
tc.reset();
}
@Test
void methodReferenceVarargs() {
public void methodReferenceVarargs() throws Exception {
TestClass5 tc = new TestClass5();
// varargs string
expression = parser.parseExpression("eleven()");
assertCantCompile(expression);
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
assertCanCompile(expression);
tc.reset();
expression.getValue(tc);
assertThat(tc.s).isEmpty();
assertThat(tc.s).isEqualTo("");
tc.reset();
// varargs string
@@ -3840,7 +3840,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference() {
public void methodReference() throws Exception {
TestClass5 tc = new TestClass5();
// non-static method, no args, void return
@@ -3985,7 +3985,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void errorHandling() {
public void errorHandling() throws Exception {
TestClass5 tc = new TestClass5();
// changing target
@@ -4040,7 +4040,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_staticMethod() {
public void methodReference_staticMethod() throws Exception {
Expression expression = parser.parseExpression("T(Integer).valueOf(42)");
int resultI = expression.getValue(new TestClass1(), Integer.TYPE);
assertCanCompile(expression);
@@ -4050,7 +4050,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_literalArguments_int() {
public void methodReference_literalArguments_int() throws Exception {
Expression expression = parser.parseExpression("'abcd'.substring(1,3)");
String resultI = expression.getValue(new TestClass1(), String.class);
assertCanCompile(expression);
@@ -4060,7 +4060,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_simpleInstanceMethodNoArg() {
public void methodReference_simpleInstanceMethodNoArg() throws Exception {
Expression expression = parser.parseExpression("toString()");
String resultI = expression.getValue(42, String.class);
assertCanCompile(expression);
@@ -4070,7 +4070,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_simpleInstanceMethodNoArgReturnPrimitive() {
public void methodReference_simpleInstanceMethodNoArgReturnPrimitive() throws Exception {
expression = parser.parseExpression("intValue()");
int resultI = expression.getValue(42, Integer.TYPE);
assertThat(resultI).isEqualTo(42);
@@ -4080,7 +4080,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() {
public void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() throws Exception {
Expression expression = parser.parseExpression("indexOf('b')");
int resultI = expression.getValue("abc", Integer.TYPE);
assertCanCompile(expression);
@@ -4090,7 +4090,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() {
public void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() throws Exception {
expression = parser.parseExpression("charAt(2)");
char resultI = expression.getValue("abc", Character.TYPE);
assertThat(resultI).isEqualTo('c');
@@ -4100,7 +4100,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void compoundExpression() {
public void compoundExpression() throws Exception {
Payload payload = new Payload();
expression = parser.parseExpression("DR[0]");
assertThat(expression.getValue(payload).toString()).isEqualTo("instanceof Two");
@@ -4137,7 +4137,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void mixingItUp_indexerOpEqTernary() {
public void mixingItUp_indexerOpEqTernary() throws Exception {
Map<String, String> m = new HashMap<>();
m.put("andy","778");
@@ -4150,7 +4150,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void propertyReference() {
public void propertyReference() throws Exception {
TestClass6 tc = new TestClass6();
// non static field
@@ -4190,7 +4190,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void propertyReferenceVisibility_SPR12771() {
public void propertyReferenceVisibility_SPR12771() {
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("httpServletRequest", HttpServlet3RequestFactory.getOne());
// Without a fix compilation was inserting a checkcast to a private type
@@ -4202,7 +4202,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
@SuppressWarnings("unchecked")
@Test
void indexer() {
public void indexer() throws Exception {
String[] sss = new String[] {"a","b","c"};
Number[] ns = new Number[] {2,8,9};
int[] is = new int[] {8,9,10};
@@ -4509,7 +4509,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void plusNeedingCheckcast_SPR12426() {
public void plusNeedingCheckcast_SPR12426() {
expression = parser.parseExpression("object + ' world'");
Object v = expression.getValue(new FooObject());
assertThat(v).isEqualTo("hello world");
@@ -4524,7 +4524,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() {
public void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() throws Exception {
Payload payload = new Payload();
expression = parser.parseExpression("DR[0].three");
@@ -4552,7 +4552,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void variantGetter() throws Exception {
public void variantGetter() throws Exception {
Payload2Holder holder = new Payload2Holder();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.addPropertyAccessor(new MyAccessor());
@@ -4566,7 +4566,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void compilerWithGenerics_12040() {
public void compilerWithGenerics_12040() {
expression = parser.parseExpression("payload!=2");
assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isTrue();
assertCanCompile(expression);
@@ -4675,7 +4675,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
// The new helper class here uses an upper bound on the generic
@Test
void compilerWithGenerics_12040_2() {
public void compilerWithGenerics_12040_2() {
expression = parser.parseExpression("payload/2");
assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2);
assertCanCompile(expression);
@@ -4719,7 +4719,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
// The other numeric operators
@Test
void compilerWithGenerics_12040_3() {
public void compilerWithGenerics_12040_3() {
expression = parser.parseExpression("payload >= 2");
assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)).isTrue();
assertCanCompile(expression);
@@ -4762,7 +4762,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void indexerMapAccessor_12045() throws Exception {
public void indexerMapAccessor_12045() throws Exception {
SpelParserConfiguration spc = new SpelParserConfiguration(
SpelCompilerMode.IMMEDIATE,getClass().getClassLoader());
SpelExpressionParser sep = new SpelExpressionParser(spc);
@@ -4791,7 +4791,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void elvisOperator_SPR15192() {
public void elvisOperator_SPR15192() {
SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null);
Expression exp;
@@ -4875,7 +4875,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void elvisOperator_SPR17214() {
public void elvisOperator_SPR17214() throws Exception {
SpelParserConfiguration spc = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null);
SpelExpressionParser sep = new SpelExpressionParser(spc);
@@ -4923,7 +4923,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void testNullComparison_SPR22358() {
public void testNullComparison_SPR22358() {
SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.OFF, null);
SpelExpressionParser parser = new SpelExpressionParser(configuration);
StandardEvaluationContext ctx = new StandardEvaluationContext();
@@ -5004,7 +5004,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void ternaryOperator_SPR15192() {
public void ternaryOperator_SPR15192() {
SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null);
Expression exp;
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -5048,9 +5048,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
// null condition
exp = new SpelExpressionParser(configuration).parseExpression("3==3?null:4L");
assertThat(exp.getValue(context, new Foo(), String.class)).isNull();
assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null);
assertCanCompile(exp);
assertThat(exp.getValue(context, new Foo(), String.class)).isNull();
assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null);
assertIsCompiled(exp);
// variable access returning primitive
@@ -5078,7 +5078,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
@Test
void repeatedCompilation() throws Exception {
public void repeatedCompilation() throws Exception {
// Verifying that after a number of compilations, the classloaders
// used to load the compiled expressions are discarded/replaced.
// See SpelCompiler.loadClass()
@@ -6204,9 +6204,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
public Reg(int v) {
this._value = v;
this._valueL = Long.valueOf(v);
this._valueD = (double) v;
this._valueF = (float) v;
this._valueL = new Long(v);
this._valueD = new Double(v);
this._valueF = new Float(v);
}
public Integer getValue() {
@@ -6243,16 +6243,16 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
public void setValue(Integer value) {
_value = value;
_valueL = value==null?null:Long.valueOf(value);
_valueD = value==null?null:Double.valueOf(value);
_valueF = value==null?null:Float.valueOf(value);
_valueL = value==null?null:new Long(value);
_valueD = value==null?null:new Double(value);
_valueF = value==null?null:new Float(value);
}
public void setValue2(Integer value) {
_value2 = value;
_valueL2 = value==null?null:Long.valueOf(value);
_valueD2 = value==null?null:Double.valueOf(value);
_valueF2 = value==null?null:Float.valueOf(value);
_valueL2 = value==null?null:new Long(value);
_valueD2 = value==null?null:new Double(value);
_valueF2 = value==null?null:new Float(value);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,35 +74,35 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Phillip Webb
* @author Sam Brannen
*/
class SpelReproTests extends AbstractExpressionTests {
public class SpelReproTests extends AbstractExpressionTests {
@Test
void NPE_SPR5661() {
public void NPE_SPR5661() {
evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class);
}
@Test
void SWF1086() {
public void SWF1086() {
evaluate("printDouble(T(java.math.BigDecimal).valueOf(14.35))", "14.35", String.class);
}
@Test
void doubleCoercion() {
public void doubleCoercion() {
evaluate("printDouble(14.35)", "14.35", String.class);
}
@Test
void doubleArrayCoercion() {
public void doubleArrayCoercion() {
evaluate("printDoubles(getDoublesAsStringList())", "{14.35, 15.45}", String.class);
}
@Test
void SPR5899() {
public void SPR5899() {
StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class());
Expression expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(12)");
assertThat(expr.getValue(context)).isEqualTo(12);
expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)");
assertThat(expr.getValue(context)).isNull();
assertThat(expr.getValue(context)).isEqualTo(null);
expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)");
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
expr::getValue);
@@ -133,7 +133,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR5905_InnerTypeReferences() {
public void SPR5905_InnerTypeReferences() {
StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class());
Expression expr = new SpelExpressionParser().parseRaw("T(java.util.Map$Entry)");
assertThat(expr.getValue(context)).isEqualTo(Map.Entry.class);
@@ -146,7 +146,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR5804() {
public void SPR5804() {
Map<String, String> m = new HashMap<>();
m.put("foo", "bar");
StandardEvaluationContext context = new StandardEvaluationContext(m); // root is a map instance
@@ -156,7 +156,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR5847() {
public void SPR5847() {
StandardEvaluationContext context = new StandardEvaluationContext(new TestProperties());
String name = null;
Expression expr = null;
@@ -192,7 +192,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void NPE_SPR5673() {
public void NPE_SPR5673() {
ParserContext hashes = TemplateExpressionParsingTests.HASH_DELIMITED_PARSER_CONTEXT;
ParserContext dollars = TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT;
@@ -227,7 +227,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void propertyAccessOnNullTarget_SPR5663() throws AccessException {
public void propertyAccessOnNullTarget_SPR5663() throws AccessException {
PropertyAccessor accessor = new ReflectivePropertyAccessor();
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
assertThat(accessor.canRead(context, null, "abc")).isFalse();
@@ -239,7 +239,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void nestedProperties_SPR6923() {
public void nestedProperties_SPR6923() {
StandardEvaluationContext context = new StandardEvaluationContext(new Foo());
Expression expr = new SpelExpressionParser().parseRaw("resource.resource.server");
String name = expr.getValue(context, String.class);
@@ -248,7 +248,7 @@ class SpelReproTests extends AbstractExpressionTests {
/** Should be accessing Goo.getKey because 'bar' field evaluates to "key" */
@Test
void indexingAsAPropertyAccess_SPR6968_1() {
public void indexingAsAPropertyAccess_SPR6968_1() {
StandardEvaluationContext context = new StandardEvaluationContext(new Goo());
String name = null;
Expression expr = null;
@@ -261,7 +261,7 @@ class SpelReproTests extends AbstractExpressionTests {
/** Should be accessing Goo.getKey because 'bar' variable evaluates to "key" */
@Test
void indexingAsAPropertyAccess_SPR6968_2() {
public void indexingAsAPropertyAccess_SPR6968_2() {
StandardEvaluationContext context = new StandardEvaluationContext(new Goo());
context.setVariable("bar", "key");
String name = null;
@@ -275,7 +275,7 @@ class SpelReproTests extends AbstractExpressionTests {
/** $ related identifiers */
@Test
void dollarPrefixedIdentifier_SPR7100() {
public void dollarPrefixedIdentifier_SPR7100() {
Holder h = new Holder();
StandardEvaluationContext context = new StandardEvaluationContext(h);
context.addPropertyAccessor(new MapAccessor());
@@ -315,7 +315,7 @@ class SpelReproTests extends AbstractExpressionTests {
/** Should be accessing Goo.wibble field because 'bar' variable evaluates to "wibble" */
@Test
void indexingAsAPropertyAccess_SPR6968_3() {
public void indexingAsAPropertyAccess_SPR6968_3() {
StandardEvaluationContext context = new StandardEvaluationContext(new Goo());
context.setVariable("bar", "wibble");
String name = null;
@@ -333,7 +333,7 @@ class SpelReproTests extends AbstractExpressionTests {
* "wibble"
*/
@Test
void indexingAsAPropertyAccess_SPR6968_4() {
public void indexingAsAPropertyAccess_SPR6968_4() {
Goo g = Goo.instance;
StandardEvaluationContext context = new StandardEvaluationContext(g);
context.setVariable("bar", "wibble");
@@ -348,7 +348,7 @@ class SpelReproTests extends AbstractExpressionTests {
/** Should be accessing Goo.setKey field because 'bar' variable evaluates to "key" */
@Test
void indexingAsAPropertyAccess_SPR6968_5() {
public void indexingAsAPropertyAccess_SPR6968_5() {
Goo g = Goo.instance;
StandardEvaluationContext context = new StandardEvaluationContext(g);
Expression expr = null;
@@ -360,7 +360,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void dollars() {
public void dollars() {
StandardEvaluationContext context = new StandardEvaluationContext(new XX());
Expression expr = null;
expr = new SpelExpressionParser().parseRaw("m['$foo']");
@@ -369,7 +369,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void dollars2() {
public void dollars2() {
StandardEvaluationContext context = new StandardEvaluationContext(new XX());
Expression expr = null;
expr = new SpelExpressionParser().parseRaw("m[$foo]");
@@ -421,7 +421,7 @@ class SpelReproTests extends AbstractExpressionTests {
};
@Test
void beanResolution() {
public void beanResolution() {
StandardEvaluationContext context = new StandardEvaluationContext(new XX());
Expression expr = null;
@@ -443,12 +443,12 @@ class SpelReproTests extends AbstractExpressionTests {
// bean does not exist
expr = new SpelExpressionParser().parseRaw("@bar");
assertThat(expr.getValue(context, String.class)).isNull();
assertThat(expr.getValue(context, String.class)).isEqualTo(null);
// bean name will cause AccessException
expr = new SpelExpressionParser().parseRaw("@goo");
try {
assertThat(expr.getValue(context, String.class)).isNull();
assertThat(expr.getValue(context, String.class)).isEqualTo(null);
}
catch (SpelEvaluationException see) {
assertThat(see.getMessageCode()).isEqualTo(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION);
@@ -472,7 +472,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void elvis_SPR7209_1() {
public void elvis_SPR7209_1() {
StandardEvaluationContext context = new StandardEvaluationContext(new XX());
Expression expr = null;
@@ -482,14 +482,14 @@ class SpelReproTests extends AbstractExpressionTests {
expr = new SpelExpressionParser().parseRaw("?:'default'");
assertThat(expr.getValue()).isEqualTo("default");
expr = new SpelExpressionParser().parseRaw("?:");
assertThat(expr.getValue()).isNull();
assertThat(expr.getValue()).isEqualTo(null);
// Different parts of ternary expression are null
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("(?'abc':'default')").getValue(context))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_CONVERSION_ERROR));
expr = new SpelExpressionParser().parseRaw("(false?'abc':null)");
assertThat(expr.getValue()).isNull();
assertThat(expr.getValue()).isEqualTo(null);
// Assignment
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
@@ -498,7 +498,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void elvis_SPR7209_2() {
public void elvis_SPR7209_2() {
Expression expr = null;
// Have empty string treated as null for elvis
expr = new SpelExpressionParser().parseRaw("?:'default'");
@@ -510,7 +510,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void mapOfMap_SPR7244() {
public void mapOfMap_SPR7244() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("uri", "http:");
Map<String, String> nameMap = new LinkedHashMap<>();
@@ -531,7 +531,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void projectionTypeDescriptors_1() {
public void projectionTypeDescriptors_1() {
StandardEvaluationContext context = new StandardEvaluationContext(new C());
SpelExpressionParser parser = new SpelExpressionParser();
String el1 = "ls.![#this.equals('abc')]";
@@ -540,11 +540,11 @@ class SpelReproTests extends AbstractExpressionTests {
// value is list containing [true,false]
assertThat(value.get(0).getClass()).isEqualTo(Boolean.class);
TypeDescriptor evaluated = exp.getValueTypeDescriptor(context);
assertThat(evaluated.getElementTypeDescriptor()).isNull();
assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null);
}
@Test
void projectionTypeDescriptors_2() {
public void projectionTypeDescriptors_2() {
StandardEvaluationContext context = new StandardEvaluationContext(new C());
SpelExpressionParser parser = new SpelExpressionParser();
String el1 = "as.![#this.equals('abc')]";
@@ -557,7 +557,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void projectionTypeDescriptors_3() {
public void projectionTypeDescriptors_3() {
StandardEvaluationContext context = new StandardEvaluationContext(new C());
SpelExpressionParser parser = new SpelExpressionParser();
String el1 = "ms.![key.equals('abc')]";
@@ -566,11 +566,11 @@ class SpelReproTests extends AbstractExpressionTests {
// value is list containing [true,false]
assertThat(value.get(0).getClass()).isEqualTo(Boolean.class);
TypeDescriptor evaluated = exp.getValueTypeDescriptor(context);
assertThat(evaluated.getElementTypeDescriptor()).isNull();
assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null);
}
@Test
void greaterThanWithNulls_SPR7840() {
public void greaterThanWithNulls_SPR7840() {
List<D> list = new ArrayList<>();
list.add(new D("aaa"));
list.add(new D("bbb"));
@@ -605,7 +605,7 @@ class SpelReproTests extends AbstractExpressionTests {
* than a unboxing conversion.
*/
@Test
void conversionPriority_SPR8224() throws Exception {
public void conversionPriority_SPR8224() throws Exception {
@SuppressWarnings("unused")
class ConversionPriority1 {
@@ -637,7 +637,7 @@ class SpelReproTests extends AbstractExpressionTests {
ConversionPriority1 target = new ConversionPriority1();
MethodExecutor me = new ReflectiveMethodResolver(true).resolve(emptyEvalContext, target, "getX", args);
// MethodInvoker chooses getX(int i) when passing Integer
final int actual = (Integer) me.execute(emptyEvalContext, target, Integer.valueOf(42)).getValue();
final int actual = (Integer) me.execute(emptyEvalContext, target, new Integer(42)).getValue();
// Compiler chooses getX(Number i) when passing Integer
final int compiler = target.getX(INTEGER);
// Fails!
@@ -646,7 +646,7 @@ class SpelReproTests extends AbstractExpressionTests {
ConversionPriority2 target2 = new ConversionPriority2();
MethodExecutor me2 = new ReflectiveMethodResolver(true).resolve(emptyEvalContext, target2, "getX", args);
// MethodInvoker chooses getX(int i) when passing Integer
int actual2 = (Integer) me2.execute(emptyEvalContext, target2, Integer.valueOf(42)).getValue();
int actual2 = (Integer) me2.execute(emptyEvalContext, target2, new Integer(42)).getValue();
// Compiler chooses getX(Number i) when passing Integer
int compiler2 = target2.getX(INTEGER);
// Fails!
@@ -659,7 +659,7 @@ class SpelReproTests extends AbstractExpressionTests {
* method accepting 'long' is ok.
*/
@Test
void wideningPrimitiveConversion_SPR8224() throws Exception {
public void wideningPrimitiveConversion_SPR8224() throws Exception {
class WideningPrimitiveConversion {
public int getX(long i) {
@@ -667,7 +667,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
}
final Integer INTEGER_VALUE = 7;
final Integer INTEGER_VALUE = Integer.valueOf(7);
WideningPrimitiveConversion target = new WideningPrimitiveConversion();
EvaluationContext emptyEvalContext = new StandardEvaluationContext();
@@ -682,7 +682,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void varargsAgainstProxy_SPR16122() {
public void varargsAgainstProxy_SPR16122() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("process('a', 'b')");
@@ -696,7 +696,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void testCompiledExpressionForProxy_SPR16191() {
public void testCompiledExpressionForProxy_SPR16191() {
SpelExpressionParser expressionParser =
new SpelExpressionParser(new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null));
Expression expression = expressionParser.parseExpression("#target.process(#root)");
@@ -715,7 +715,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void varargsAndPrimitives_SPR8174() throws Exception {
public void varargsAndPrimitives_SPR8174() throws Exception {
EvaluationContext emptyEvalContext = new StandardEvaluationContext();
List<TypeDescriptor> args = new ArrayList<>();
@@ -763,7 +763,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void reservedWords_SPR8228() {
public void reservedWords_SPR8228() {
// "DIV","EQ","GE","GT","LE","LT","MOD","NE","NOT"
@SuppressWarnings("unused")
@@ -814,7 +814,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void reservedWordProperties_SPR9862() {
public void reservedWordProperties_SPR9862() {
StandardEvaluationContext context = new StandardEvaluationContext();
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expression = parser.parseRaw("T(org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver).CONST");
@@ -829,7 +829,7 @@ class SpelReproTests extends AbstractExpressionTests {
* in evaluation of SPEL expressions for a given context.
*/
@Test
void propertyAccessorOrder_SPR8211() {
public void propertyAccessorOrder_SPR8211() {
ExpressionParser expressionParser = new SpelExpressionParser();
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new ContextObject());
@@ -849,7 +849,7 @@ class SpelReproTests extends AbstractExpressionTests {
* determines the set of methods for a type.
*/
@Test
void customStaticFunctions_SPR9038() {
public void customStaticFunctions_SPR9038() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
List<MethodResolver> methodResolvers = new ArrayList<>();
@@ -873,7 +873,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void array() {
public void array() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
Expression expression = null;
@@ -902,7 +902,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatFunctionResolver() {
public void SPR9486_floatFunctionResolver() {
Number expectedResult = Math.abs(-10.2f);
ExpressionParser parser = new SpelExpressionParser();
SPR9486_FunctionsClass testObject = new SPR9486_FunctionsClass();
@@ -914,7 +914,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_addFloatWithDouble() {
public void SPR9486_addFloatWithDouble() {
Number expectedNumber = 10.21f + 10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -924,7 +924,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_addFloatWithFloat() {
public void SPR9486_addFloatWithFloat() {
Number expectedNumber = 10.21f + 10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -934,7 +934,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_subtractFloatWithDouble() {
public void SPR9486_subtractFloatWithDouble() {
Number expectedNumber = 10.21f - 10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -944,7 +944,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_subtractFloatWithFloat() {
public void SPR9486_subtractFloatWithFloat() {
Number expectedNumber = 10.21f - 10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -954,7 +954,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_multiplyFloatWithDouble() {
public void SPR9486_multiplyFloatWithDouble() {
Number expectedNumber = 10.21f * 10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -964,7 +964,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_multiplyFloatWithFloat() {
public void SPR9486_multiplyFloatWithFloat() {
Number expectedNumber = 10.21f * 10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -974,7 +974,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatDivideByFloat() {
public void SPR9486_floatDivideByFloat() {
Number expectedNumber = -10.21f / -10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -984,7 +984,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatDivideByDouble() {
public void SPR9486_floatDivideByDouble() {
Number expectedNumber = -10.21f / -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -994,7 +994,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatEqFloatUnaryMinus() {
public void SPR9486_floatEqFloatUnaryMinus() {
Boolean expectedResult = -10.21f == -10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1004,7 +1004,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatEqDoubleUnaryMinus() {
public void SPR9486_floatEqDoubleUnaryMinus() {
Boolean expectedResult = -10.21f == -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1014,7 +1014,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatEqFloat() {
public void SPR9486_floatEqFloat() {
Boolean expectedResult = 10.215f == 10.2109f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1024,7 +1024,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatEqDouble() {
public void SPR9486_floatEqDouble() {
Boolean expectedResult = 10.215f == 10.2109;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1034,7 +1034,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatNotEqFloat() {
public void SPR9486_floatNotEqFloat() {
Boolean expectedResult = 10.215f != 10.2109f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1044,7 +1044,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatNotEqDouble() {
public void SPR9486_floatNotEqDouble() {
Boolean expectedResult = 10.215f != 10.2109;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1054,7 +1054,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatLessThanFloat() {
public void SPR9486_floatLessThanFloat() {
Boolean expectedNumber = -10.21f < -10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1064,7 +1064,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatLessThanDouble() {
public void SPR9486_floatLessThanDouble() {
Boolean expectedNumber = -10.21f < -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1074,7 +1074,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatLessThanOrEqualFloat() {
public void SPR9486_floatLessThanOrEqualFloat() {
Boolean expectedNumber = -10.21f <= -10.22f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1084,7 +1084,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatLessThanOrEqualDouble() {
public void SPR9486_floatLessThanOrEqualDouble() {
Boolean expectedNumber = -10.21f <= -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1094,7 +1094,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatGreaterThanFloat() {
public void SPR9486_floatGreaterThanFloat() {
Boolean expectedNumber = -10.21f > -10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1104,7 +1104,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatGreaterThanDouble() {
public void SPR9486_floatGreaterThanDouble() {
Boolean expectedResult = -10.21f > -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1114,7 +1114,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatGreaterThanOrEqualFloat() {
public void SPR9486_floatGreaterThanOrEqualFloat() {
Boolean expectedNumber = -10.21f >= -10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1124,7 +1124,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatGreaterThanEqualDouble() {
public void SPR9486_floatGreaterThanEqualDouble() {
Boolean expectedResult = -10.21f >= -10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1134,7 +1134,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatModulusFloat() {
public void SPR9486_floatModulusFloat() {
Number expectedResult = 10.21f % 10.2f;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1144,7 +1144,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatModulusDouble() {
public void SPR9486_floatModulusDouble() {
Number expectedResult = 10.21f % 10.2;
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1154,7 +1154,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatPowerFloat() {
public void SPR9486_floatPowerFloat() {
Number expectedResult = Math.pow(10.21f, -10.2f);
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1164,7 +1164,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9486_floatPowerDouble() {
public void SPR9486_floatPowerDouble() {
Number expectedResult = Math.pow(10.21f, 10.2);
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -1174,7 +1174,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9994_bridgeMethods() throws Exception {
public void SPR9994_bridgeMethods() throws Exception {
ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor();
StandardEvaluationContext context = new StandardEvaluationContext();
GenericImplementation target = new GenericImplementation();
@@ -1187,7 +1187,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10162_onlyBridgeMethod() throws Exception {
public void SPR10162_onlyBridgeMethod() throws Exception {
ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor();
StandardEvaluationContext context = new StandardEvaluationContext();
Object target = new OnlyBridgeMethod();
@@ -1197,7 +1197,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10091_simpleTestValueType() {
public void SPR10091_simpleTestValueType() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
Class<?> valueType = parser.parseExpression("simpleProperty").getValueType(evaluationContext);
@@ -1205,7 +1205,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10091_simpleTestValue() {
public void SPR10091_simpleTestValue() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
Object value = parser.parseExpression("simpleProperty").getValue(evaluationContext);
@@ -1213,7 +1213,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10091_primitiveTestValueType() {
public void SPR10091_primitiveTestValueType() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
Class<?> valueType = parser.parseExpression("primitiveProperty").getValueType(evaluationContext);
@@ -1221,7 +1221,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10091_primitiveTestValue() {
public void SPR10091_primitiveTestValue() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder());
Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext);
@@ -1229,7 +1229,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR16123() {
public void SPR16123() {
ExpressionParser parser = new SpelExpressionParser();
parser.parseExpression("simpleProperty").setValue(new BooleanHolder(), null);
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
@@ -1237,7 +1237,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10146_malformedExpressions() {
public void SPR10146_malformedExpressions() {
doTestSpr10146("/foo", "EL1070E: Problem parsing left operand");
doTestSpr10146("*foo", "EL1070E: Problem parsing left operand");
doTestSpr10146("%foo", "EL1070E: Problem parsing left operand");
@@ -1255,7 +1255,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10125() {
public void SPR10125() {
StandardEvaluationContext context = new StandardEvaluationContext();
String fromInterface = parser.parseExpression("T(" + StaticFinalImpl1.class.getName() + ").VALUE").getValue(
context, String.class);
@@ -1266,7 +1266,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10210() {
public void SPR10210() {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D());
Expression parseExpression = parser.parseExpression("#bridgeExample.bridgeMethod()");
@@ -1274,14 +1274,14 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10328() {
public void SPR10328() {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
parser.parseExpression("$[]"))
.withMessageContaining("EL1071E: A required selection expression has not been specified");
}
@Test
void SPR10452() {
public void SPR10452() {
SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
ExpressionParser parser = new SpelExpressionParser(configuration);
@@ -1306,7 +1306,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9495() {
public void SPR9495() {
SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
ExpressionParser parser = new SpelExpressionParser(configuration);
@@ -1347,7 +1347,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR10486() {
public void SPR10486() {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
Spr10486 rootObject = new Spr10486();
@@ -1358,7 +1358,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR11142() {
public void SPR11142() {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
Spr11142 rootObject = new Spr11142();
@@ -1369,7 +1369,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9194() {
public void SPR9194() {
TestClass2 one = new TestClass2("abc");
TestClass2 two = new TestClass2("abc");
Map<String, TestClass2> map = new HashMap<>();
@@ -1382,7 +1382,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR11348() {
public void SPR11348() {
Collection<String> coll = new LinkedHashSet<>();
coll.add("one");
coll.add("two");
@@ -1399,14 +1399,14 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR11445_simple() {
public void SPR11445_simple() {
StandardEvaluationContext context = new StandardEvaluationContext(new Spr11445Class());
Expression expr = new SpelExpressionParser().parseRaw("echo(parameter())");
assertThat(expr.getValue(context)).isEqualTo(1);
}
@Test
void SPR11445_beanReference() {
public void SPR11445_beanReference() {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new Spr11445Class());
Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())");
@@ -1415,14 +1415,14 @@ class SpelReproTests extends AbstractExpressionTests {
@Test
@SuppressWarnings("unchecked")
void SPR11494() {
public void SPR11494() {
Expression exp = new SpelExpressionParser().parseExpression("T(java.util.Arrays).asList('a','b')");
List<String> list = (List<String>) exp.getValue();
assertThat(list).hasSize(2);
}
@Test
void SPR11609() {
public void SPR11609() {
StandardEvaluationContext sec = new StandardEvaluationContext();
sec.addPropertyAccessor(new MapAccessor());
Expression exp = new SpelExpressionParser().parseExpression(
@@ -1431,7 +1431,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR9735() {
public void SPR9735() {
Item item = new Item();
item.setName("parent");
@@ -1453,7 +1453,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR12502() {
public void SPR12502() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("#root.getClass().getName()");
assertThat(expression.getValue(new UnnamedUser())).isEqualTo(UnnamedUser.class.getName());
@@ -1462,7 +1462,7 @@ class SpelReproTests extends AbstractExpressionTests {
@Test
@SuppressWarnings("rawtypes")
void SPR12522() {
public void SPR12522() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("T(java.util.Arrays).asList('')");
Object value = expression.getValue();
@@ -1471,7 +1471,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR12803() {
public void SPR12803() {
StandardEvaluationContext sec = new StandardEvaluationContext();
sec.setVariable("iterable", Collections.emptyList());
SpelExpressionParser parser = new SpelExpressionParser();
@@ -1480,7 +1480,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR12808() {
public void SPR12808() {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("T(org.springframework.expression.spel.SpelReproTests.DistanceEnforcer).from(#no)");
StandardEvaluationContext sec = new StandardEvaluationContext();
@@ -1496,7 +1496,7 @@ class SpelReproTests extends AbstractExpressionTests {
@Test
@SuppressWarnings("rawtypes")
void SPR13055() {
public void SPR13055() {
List<Map<String, Object>> myPayload = new ArrayList<>();
Map<String, Object> v1 = new HashMap<>();
@@ -1527,7 +1527,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void AccessingFactoryBean_spr9511() {
public void AccessingFactoryBean_spr9511() {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());
Expression expr = new SpelExpressionParser().parseRaw("@foo");
@@ -1551,7 +1551,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR12035() {
public void SPR12035() {
ExpressionParser parser = new SpelExpressionParser();
Expression expression1 = parser.parseExpression("list.?[ value>2 ].size()!=0");
@@ -1562,7 +1562,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR13055_maps() {
public void SPR13055_maps() {
EvaluationContext context = new StandardEvaluationContext();
ExpressionParser parser = new SpelExpressionParser();
@@ -1578,7 +1578,7 @@ class SpelReproTests extends AbstractExpressionTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void SPR10417() {
public void SPR10417() {
List list1 = new ArrayList();
list1.add("a");
list1.add("b");
@@ -1619,7 +1619,7 @@ class SpelReproTests extends AbstractExpressionTests {
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
void SPR10417_maps() {
public void SPR10417_maps() {
Map map1 = new HashMap();
map1.put("A", 65);
map1.put("B", 66);
@@ -1642,7 +1642,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR13918() {
public void SPR13918() {
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("encoding", "UTF-8");
@@ -1652,7 +1652,7 @@ class SpelReproTests extends AbstractExpressionTests {
}
@Test
void SPR16032() {
public void SPR16032() {
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("str", "a\0b");
+5 -5
View File
@@ -3,9 +3,9 @@ description = "Spring JDBC"
apply plugin: "kotlin"
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
api(project(":spring-tx"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
compile(project(":spring-tx"))
optional(project(":spring-context")) // for JndiDataSourceLookup
optional("javax.transaction:javax.transaction-api")
optional("org.hsqldb:hsqldb")
@@ -14,6 +14,6 @@ dependencies {
optional("org.apache.derby:derbyclient")
optional("org.jetbrains.kotlin:kotlin-reflect")
optional("org.jetbrains.kotlin:kotlin-stdlib")
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-core")))
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-core")))
}
+7 -7
View File
@@ -1,10 +1,10 @@
description = "Spring JMS"
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
api(project(":spring-messaging"))
api(project(":spring-tx"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
compile(project(":spring-messaging"))
compile(project(":spring-tx"))
compileOnly("javax.jms:javax.jms-api")
optional(project(":spring-aop"))
optional(project(":spring-context"))
@@ -12,8 +12,8 @@ dependencies {
optional("javax.resource:javax.resource-api")
optional("javax.transaction:javax.transaction-api")
optional("com.fasterxml.jackson.core:jackson-databind")
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-tx")))
testImplementation("org.apache.activemq:activemq-broker")
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-tx")))
testCompile("org.apache.activemq:activemq-broker")
testImplementation("javax.jms:javax.jms-api")
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -92,7 +92,6 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B
private ClassLoader beanClassLoader;
@SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean)
public MappingJackson2MessageConverter() {
this.objectMapper = new ObjectMapper();
this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 javax.jms.Session;
import javax.jms.TextMessage;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.jms.support.converter.MessageConversionException;
@@ -50,7 +51,7 @@ import static org.mockito.Mockito.verify;
* @author Juergen Hoeller
* @author Chris Beams
*/
class MessageListenerAdapterTests {
public class MessageListenerAdapterTests {
private static final String TEXT = "I fancy a good cuppa right now";
@@ -64,7 +65,7 @@ class MessageListenerAdapterTests {
@Test
void testWithMessageContentsDelegateForTextMessage() throws Exception {
public void testWithMessageContentsDelegateForTextMessage() throws Exception {
TextMessage textMessage = mock(TextMessage.class);
// TextMessage contents must be unwrapped...
given(textMessage.getText()).willReturn(TEXT);
@@ -78,14 +79,17 @@ class MessageListenerAdapterTests {
}
@Test
void testWithMessageContentsDelegateForBytesMessage() throws Exception {
public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
BytesMessage bytesMessage = mock(BytesMessage.class);
// BytesMessage contents must be unwrapped...
given(bytesMessage.getBodyLength()).willReturn(Long.valueOf(TEXT.getBytes().length));
given(bytesMessage.readBytes(any(byte[].class))).willAnswer((Answer<Integer>) invocation -> {
byte[] bytes = (byte[]) invocation.getArguments()[0];
ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes());
return inputStream.read(bytes);
given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length));
given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() {
@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);
@@ -97,7 +101,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithMessageContentsDelegateForObjectMessage() throws Exception {
public void testWithMessageContentsDelegateForObjectMessage() throws Exception {
ObjectMessage objectMessage = mock(ObjectMessage.class);
given(objectMessage.getObject()).willReturn(NUMBER);
@@ -110,7 +114,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
ObjectMessage objectMessage = mock(ObjectMessage.class);
given(objectMessage.getObject()).willReturn(OBJECT);
@@ -123,7 +127,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithMessageDelegate() throws Exception {
public void testWithMessageDelegate() throws Exception {
TextMessage textMessage = mock(TextMessage.class);
MessageDelegate delegate = mock(MessageDelegate.class);
@@ -137,7 +141,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWhenTheAdapterItselfIsTheDelegate() throws Exception {
public void testWhenTheAdapterItselfIsTheDelegate() throws Exception {
TextMessage textMessage = mock(TextMessage.class);
// TextMessage contents must be unwrapped...
given(textMessage.getText()).willReturn(TEXT);
@@ -148,7 +152,7 @@ class MessageListenerAdapterTests {
}
@Test
void testRainyDayWithNoApplicableHandlingMethods() throws Exception {
public void testRainyDayWithNoApplicableHandlingMethods() throws Exception {
TextMessage textMessage = mock(TextMessage.class);
// TextMessage contents must be unwrapped...
given(textMessage.getText()).willReturn(TEXT);
@@ -160,7 +164,7 @@ class MessageListenerAdapterTests {
}
@Test
void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception {
public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception {
final IllegalArgumentException exception = new IllegalArgumentException();
TextMessage textMessage = mock(TextMessage.class);
@@ -185,7 +189,7 @@ class MessageListenerAdapterTests {
}
@Test
void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception {
public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertThat(adapter.getMessageConverter()).as("The default [MessageConverter] must never be null.").isNotNull();
boolean condition = adapter.getMessageConverter() instanceof SimpleMessageConverter;
@@ -193,19 +197,19 @@ class MessageListenerAdapterTests {
}
@Test
void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception {
public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertThat(adapter.getDelegate()).isSameAs(adapter);
}
@Test
void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception {
public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception {
MessageListenerAdapter adapter = new MessageListenerAdapter();
assertThat(adapter.getDefaultListenerMethod()).isEqualTo(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD);
}
@Test
void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
TextMessage textMessage = mock(TextMessage.class);
ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
given(delegate.handleMessage(textMessage)).willReturn(TEXT);
@@ -217,7 +221,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
Queue destination = mock(Queue.class);
TextMessage sentTextMessage = mock(TextMessage.class);
// correlation ID is queried when response is being created...
@@ -252,7 +256,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
Queue destination = mock(Queue.class);
TextMessage sentTextMessage = mock(TextMessage.class);
// correlation ID is queried when response is being created...
@@ -285,7 +289,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
final TextMessage sentTextMessage = mock(TextMessage.class);
// correlation ID is queried when response is being created...
given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID);
@@ -314,7 +318,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
Queue destination = mock(Queue.class);
final TextMessage sentTextMessage = mock(TextMessage.class);
@@ -350,7 +354,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
final TextMessage message = mock(TextMessage.class);
final QueueSession session = mock(QueueSession.class);
@@ -368,7 +372,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
final TextMessage sentTextMessage = mock(TextMessage.class);
final Session session = mock(Session.class);
ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
@@ -387,7 +391,7 @@ class MessageListenerAdapterTests {
}
@Test
void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
Queue destination = mock(Queue.class);
final TextMessage sentTextMessage = mock(TextMessage.class);
// correlation ID is queried when response is being created...
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 javax.jms.TextMessage;
import com.fasterxml.jackson.annotation.JsonView;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.core.MethodParameter;
@@ -48,7 +49,7 @@ import static org.mockito.Mockito.verify;
* @author Dave Syer
* @author Stephane Nicoll
*/
class MappingJackson2MessageConverterTests {
public class MappingJackson2MessageConverterTests {
private MappingJackson2MessageConverter converter;
@@ -65,7 +66,7 @@ class MappingJackson2MessageConverterTests {
@Test
void toBytesMessage() throws Exception {
public void toBytesMessage() throws Exception {
BytesMessage bytesMessageMock = mock(BytesMessage.class);
Date toBeMarshalled = new Date();
@@ -79,7 +80,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void fromBytesMessage() throws Exception {
public void fromBytesMessage() throws Exception {
BytesMessage bytesMessageMock = mock(BytesMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar");
@@ -88,16 +89,21 @@ class MappingJackson2MessageConverterTests {
given(bytesMessageMock.getStringProperty("__typeid__")).willReturn(Object.class.getName());
given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false);
given(bytesMessageMock.getBodyLength()).willReturn(Long.valueOf(bytes.length));
given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length));
given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer(
(Answer<Integer>) invocation -> byteStream.read((byte[]) invocation.getArguments()[0]));
new Answer<Integer>() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return byteStream.read((byte[]) invocation.getArguments()[0]);
}
});
Object result = converter.fromMessage(bytesMessageMock);
assertThat(unmarshalled).as("Invalid result").isEqualTo(result);
}
@Test
void toTextMessageWithObject() throws Exception {
public void toTextMessageWithObject() throws Exception {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = mock(TextMessage.class);
Date toBeMarshalled = new Date();
@@ -109,7 +115,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithMap() throws Exception {
public void toTextMessageWithMap() throws Exception {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = mock(TextMessage.class);
Map<String, String> toBeMarshalled = new HashMap<>();
@@ -122,7 +128,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void fromTextMessage() throws Exception {
public void fromTextMessage() throws Exception {
TextMessage textMessageMock = mock(TextMessage.class);
MyBean unmarshalled = new MyBean("bar");
@@ -135,7 +141,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void fromTextMessageWithUnknownProperty() throws Exception {
public void fromTextMessageWithUnknownProperty() throws Exception {
TextMessage textMessageMock = mock(TextMessage.class);
MyBean unmarshalled = new MyBean("bar");
@@ -148,7 +154,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void fromTextMessageAsObject() throws Exception {
public void fromTextMessageAsObject() throws Exception {
TextMessage textMessageMock = mock(TextMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar");
@@ -161,7 +167,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void fromTextMessageAsMap() throws Exception {
public void fromTextMessageAsMap() throws Exception {
TextMessage textMessageMock = mock(TextMessage.class);
Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar");
@@ -174,7 +180,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithReturnType() throws JMSException, NoSuchMethodException {
public void toTextMessageWithReturnType() throws JMSException, NoSuchMethodException {
Method method = this.getClass().getDeclaredMethod("summary");
MethodParameter returnType = new MethodParameter(method, -1);
testToTextMessageWithReturnType(returnType);
@@ -182,13 +188,13 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithNullReturnType() throws JMSException, NoSuchMethodException {
public void toTextMessageWithNullReturnType() throws JMSException, NoSuchMethodException {
testToTextMessageWithReturnType(null);
verify(sessionMock).createTextMessage("{\"name\":\"test\",\"description\":\"lengthy description\"}");
}
@Test
void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSuchMethodException {
public void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSuchMethodException {
Method method = this.getClass().getDeclaredMethod("none");
MethodParameter returnType = new MethodParameter(method, -1);
@@ -197,7 +203,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithReturnTypeAndMultipleJsonViews() throws JMSException, NoSuchMethodException {
public void toTextMessageWithReturnTypeAndMultipleJsonViews() throws JMSException, NoSuchMethodException {
Method method = this.getClass().getDeclaredMethod("invalid");
MethodParameter returnType = new MethodParameter(method, -1);
@@ -216,7 +222,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithJsonViewClass() throws JMSException {
public void toTextMessageWithJsonViewClass() throws JMSException {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = mock(TextMessage.class);
@@ -230,7 +236,7 @@ class MappingJackson2MessageConverterTests {
}
@Test
void toTextMessageWithAnotherJsonViewClass() throws JMSException {
public void toTextMessageWithAnotherJsonViewClass() throws JMSException {
converter.setTargetType(MessageType.TEXT);
TextMessage textMessageMock = mock(TextMessage.class);
+24 -22
View File
@@ -4,8 +4,9 @@ apply plugin: "kotlin"
apply plugin: "kotlinx-serialization"
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
compileOnly(project(":kotlin-coroutines"))
optional(project(":spring-context"))
optional(project(":spring-oxm"))
optional("io.projectreactor.netty:reactor-netty-http")
@@ -18,24 +19,25 @@ dependencies {
optional("com.google.protobuf:protobuf-java-util")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
optional("org.jetbrains.kotlinx:kotlinx-serialization-json")
testImplementation(testFixtures(project(":spring-core")))
testImplementation("javax.inject:javax.inject-tck")
testImplementation("javax.servlet:javax.servlet-api")
testImplementation("javax.validation:validation-api")
testImplementation("com.thoughtworks.xstream:xstream")
testImplementation("org.apache.activemq:activemq-broker")
testImplementation("org.apache.activemq:activemq-kahadb-store")
testImplementation("org.apache.activemq:activemq-stomp")
testImplementation("io.projectreactor:reactor-test")
testImplementation("io.reactivex.rxjava3:rxjava")
testImplementation("org.jetbrains.kotlin:kotlin-reflect")
testImplementation("org.jetbrains.kotlin:kotlin-stdlib")
testImplementation("org.xmlunit:xmlunit-assertj")
testImplementation("org.xmlunit:xmlunit-matchers")
testRuntimeOnly("com.sun.activation:javax.activation")
testRuntimeOnly("com.sun.xml.bind:jaxb-core")
testRuntimeOnly("com.sun.xml.bind:jaxb-impl")
testRuntimeOnly("javax.json:javax.json-api")
testRuntimeOnly("org.apache.johnzon:johnzon-jsonb")
testRuntimeOnly(project(":spring-context"))
testCompile(project(":kotlin-coroutines"))
testCompile(testFixtures(project(":spring-core")))
testCompile("javax.inject:javax.inject-tck")
testCompile("javax.servlet:javax.servlet-api")
testCompile("javax.validation:validation-api")
testCompile("com.thoughtworks.xstream:xstream")
testCompile("org.apache.activemq:activemq-broker")
testCompile("org.apache.activemq:activemq-kahadb-store")
testCompile("org.apache.activemq:activemq-stomp")
testCompile("io.projectreactor:reactor-test")
testCompile "io.reactivex.rxjava3:rxjava"
testCompile("org.jetbrains.kotlin:kotlin-reflect")
testCompile("org.jetbrains.kotlin:kotlin-stdlib")
testCompile("org.xmlunit:xmlunit-assertj")
testCompile("org.xmlunit:xmlunit-matchers")
testRuntime("com.sun.activation:javax.activation")
testRuntime("com.sun.xml.bind:jaxb-core")
testRuntime("com.sun.xml.bind:jaxb-impl")
testRuntime("javax.json:javax.json-api")
testRuntime("org.apache.johnzon:johnzon-jsonb")
testRuntime(project(":spring-context"))
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -88,7 +88,6 @@ public class MappingJackson2MessageConverter extends AbstractMessageConverter {
}
@SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean)
private ObjectMapper initObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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,6 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
@@ -88,7 +87,6 @@ public class HandlerMethod {
this.beanType = ClassUtils.getUserClass(bean);
this.method = method;
this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
ReflectionUtils.makeAccessible(this.bridgedMethod);
this.parameters = initMethodParameters();
}
@@ -104,7 +102,6 @@ public class HandlerMethod {
this.beanType = ClassUtils.getUserClass(bean);
this.method = bean.getClass().getMethod(methodName, parameterTypes);
this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(this.method);
ReflectionUtils.makeAccessible(this.bridgedMethod);
this.parameters = initMethodParameters();
}
@@ -126,7 +123,6 @@ public class HandlerMethod {
this.beanType = ClassUtils.getUserClass(beanType);
this.method = method;
this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
ReflectionUtils.makeAccessible(this.bridgedMethod);
this.parameters = initMethodParameters();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@@ -320,12 +319,9 @@ public abstract class AbstractMethodMessageHandler<T>
}
private String formatMappings(Class<?> userType, Map<Method, T> methods) {
String packageName = ClassUtils.getPackageName(userType);
String formattedType = (StringUtils.hasText(packageName) ?
Arrays.stream(packageName.split("\\."))
.map(packageSegment -> packageSegment.substring(0, 1))
.collect(Collectors.joining(".", "", "." + userType.getSimpleName())) :
userType.getSimpleName());
String formattedType = Arrays.stream(ClassUtils.getPackageName(userType).split("\\."))
.map(p -> p.substring(0, 1))
.collect(Collectors.joining(".", "", "." + userType.getSimpleName()));
Function<Method, String> methodFormatter = method -> Arrays.stream(method.getParameterTypes())
.map(Class::getSimpleName)
.collect(Collectors.joining(",", "(", ")"));
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,6 +29,7 @@ import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* Extension of {@link HandlerMethod} that invokes the underlying method with
@@ -165,6 +166,7 @@ public class InvocableHandlerMethod extends HandlerMethod {
*/
@Nullable
protected Object doInvoke(Object... args) throws Exception {
ReflectionUtils.makeAccessible(getBridgedMethod());
try {
return getBridgedMethod().invoke(getBean(), args);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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,6 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.RouteMatcher;
import org.springframework.util.StringUtils;
/**
* Abstract base class for reactive HandlerMethod-based message handling.
@@ -342,12 +341,9 @@ public abstract class AbstractMethodMessageHandler<T>
}
private String formatMappings(Class<?> userType, Map<Method, T> methods) {
String packageName = ClassUtils.getPackageName(userType);
String formattedType = (StringUtils.hasText(packageName) ?
Arrays.stream(packageName.split("\\."))
.map(packageSegment -> packageSegment.substring(0, 1))
.collect(Collectors.joining(".", "", "." + userType.getSimpleName())) :
userType.getSimpleName());
String formattedType = Arrays.stream(ClassUtils.getPackageName(userType).split("\\."))
.map(p -> p.substring(0, 1))
.collect(Collectors.joining(".", "", "." + userType.getSimpleName()));
Function<Method, String> methodFormatter = method -> Arrays.stream(method.getParameterTypes())
.map(Class::getSimpleName)
.collect(Collectors.joining(",", "(", ")"));
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,6 +38,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* Extension of {@link HandlerMethod} that invokes the underlying method with
@@ -129,6 +130,7 @@ public class InvocableHandlerMethod extends HandlerMethod {
boolean isSuspendingFunction = false;
try {
Method method = getBridgedMethod();
ReflectionUtils.makeAccessible(method);
if (KotlinDetector.isSuspendingFunction(method)) {
isSuspendingFunction = true;
value = CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);
@@ -83,7 +83,7 @@ import org.springframework.validation.Validator;
* </ul>
*
* <p>{@link #brokerChannel} delivers messages from within the application to the
* respective message handlers. {@link #brokerMessagingTemplate} can be injected
* the respective message handlers. {@link #brokerMessagingTemplate} can be injected
* into any application component to send messages.
*
* <p>Subclasses are responsible for the parts of the configuration that feed messages
+12 -12
View File
@@ -1,21 +1,21 @@
description = "Spring Object/Relational Mapping"
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
api(project(":spring-jdbc"))
api(project(":spring-tx"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
compile(project(":spring-jdbc"))
compile(project(":spring-tx"))
optional(project(":spring-aop"))
optional(project(":spring-context"))
optional(project(":spring-web"))
optional("org.eclipse.persistence:org.eclipse.persistence.jpa")
optional("org.hibernate:hibernate-core")
optional("javax.servlet:javax.servlet-api")
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-context")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation(testFixtures(project(":spring-web")))
testImplementation("org.aspectj:aspectjweaver")
testImplementation("org.hsqldb:hsqldb")
testRuntimeOnly("javax.xml.bind:jaxb-api")
optional("javax.servlet:javax.servlet-api:3.1.0")
testCompile(testFixtures(project(":spring-beans")))
testCompile(testFixtures(project(":spring-context")))
testCompile(testFixtures(project(":spring-core")))
testCompile(testFixtures(project(":spring-web")))
testCompile("org.aspectj:aspectjweaver")
testCompile("org.hsqldb:hsqldb")
testRuntime("javax.xml.bind:jaxb-api")
}
+12 -13
View File
@@ -16,7 +16,6 @@ dependencies {
xjc {
xjcVersion = '2.2'
}
sourceSets {
test {
xjcTargetPackage = 'org.springframework.oxm.jaxb.test'
@@ -24,23 +23,23 @@ sourceSets {
}
dependencies {
api(project(":spring-beans"))
api(project(":spring-core"))
compile(project(":spring-beans"))
compile(project(":spring-core"))
optional("javax.xml.bind:jaxb-api")
optional("javax.activation:javax.activation-api")
optional("com.thoughtworks.xstream:xstream")
optional("org.jibx:jibx-run")
testImplementation(project(":spring-context"))
testImplementation(testFixtures(project(":spring-core")))
testImplementation("org.ogce:xpp3")
testImplementation("org.codehaus.jettison:jettison") {
testCompile(project(":spring-context"))
testCompile(testFixtures(project(":spring-core")))
testCompile("org.ogce:xpp3")
testCompile("org.codehaus.jettison:jettison") {
exclude group: "stax", module: "stax-api"
}
//testImplementation(files(genJaxb.classesDir).builtBy(genJaxb))
testImplementation("org.xmlunit:xmlunit-assertj")
testImplementation("org.xmlunit:xmlunit-matchers")
testRuntimeOnly("com.sun.xml.bind:jaxb-core")
testRuntimeOnly("com.sun.xml.bind:jaxb-impl")
//testCompile(files(genJaxb.classesDir).builtBy(genJaxb))
testCompile("org.xmlunit:xmlunit-assertj")
testCompile("org.xmlunit:xmlunit-matchers")
testRuntime("com.sun.xml.bind:jaxb-core")
testRuntime("com.sun.xml.bind:jaxb-impl")
}
// JiBX compiler is currently not compatible with JDK 9+.
@@ -56,7 +55,7 @@ if ((JavaVersion.current() == JavaVersion.VERSION_1_8) && !project.hasProperty("
classpath: configurations.jibx.asPath)
jibx(verbose: false, load: true, binding: bindingXml) {
classpathset(dir: sourceSets.test.java.classesDirectory.get().getAsFile()) {
classpathset(dir: sourceSets.test.java.outputDir) {
include(name: "**/jibx/**/*")
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,8 +63,6 @@ import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.security.ForbiddenClassException;
import com.thoughtworks.xstream.security.TypePermission;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -108,7 +106,7 @@ import org.springframework.util.xml.StaxUtils;
* Therefore, it has limited namespace support. As such, it is rather unsuitable for
* usage within Web Services.
*
* <p>This marshaller requires XStream 1.4.7 or higher, as of Spring 5.2.17.
* <p>This marshaller requires XStream 1.4.5 or higher, as of Spring 4.3.
* Note that {@link XStream} construction has been reworked in 4.0, with the
* stream driver and the class loader getting passed into XStream itself now.
*
@@ -148,9 +146,6 @@ public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLo
@Nullable
private ConverterMatcher[] converters;
@Nullable
private TypePermission[] typePermissions;
@Nullable
private MarshallingStrategy marshallingStrategy;
@@ -273,20 +268,6 @@ public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLo
this.converters = converters;
}
/**
* Set XStream type permissions such as
* {@link com.thoughtworks.xstream.security.AnyTypePermission},
* {@link com.thoughtworks.xstream.security.ExplicitTypePermission} etc,
* as an alternative to overriding the {@link #customizeXStream} method.
* <p>Note: As of XStream 1.4.18, the default type permissions are
* restricted to well-known core JDK types. For any custom types,
* explicit type permissions need to be registered.
* @since 5.2.17
*/
public void setTypePermissions(TypePermission... typePermissions) {
this.typePermissions = typePermissions;
}
/**
* Set a custom XStream {@link MarshallingStrategy} to use.
* @since 4.0
@@ -426,7 +407,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLo
@Override
public void afterPropertiesSet() {
// no-op due to use of SingletonSupplier for the XStream field
// no-op due to use of SingletonSupplier for the XStream field.
}
/**
@@ -498,12 +479,6 @@ public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLo
}
}
if (this.typePermissions != null) {
for (TypePermission permission : this.typePermissions) {
xstream.addPermission(permission);
}
}
if (this.marshallingStrategy != null) {
xstream.setMarshallingStrategy(this.marshallingStrategy);
}
@@ -869,7 +844,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements BeanClassLo
*/
protected XmlMappingException convertXStreamException(Exception ex, boolean marshalling) {
if (ex instanceof StreamException || ex instanceof CannotResolveClassException ||
ex instanceof ForbiddenClassException || ex instanceof ConversionException) {
ex instanceof ConversionException) {
if (marshalling) {
return new MarshallingFailureException("XStream marshalling exception", ex);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2020 the original author 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,7 +43,6 @@ import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
@@ -68,21 +67,18 @@ import static org.mockito.Mockito.mock;
/**
* @author Arjen Poutsma
* @author Sam Brannen
* @author Juergen Hoeller
*/
class XStreamMarshallerTests {
private static final String EXPECTED_STRING = "<flight><flightNumber>42</flightNumber></flight>";
private final Flight flight = new Flight();
private final XStreamMarshaller marshaller = new XStreamMarshaller();
private XStreamMarshaller marshaller;
private final Flight flight = new Flight();
@BeforeEach
void createMarshaller() {
marshaller = new XStreamMarshaller();
marshaller.setTypePermissions(AnyTypePermission.ANY);
marshaller.setAliases(Collections.singletonMap("flight", Flight.class.getName()));
flight.setFlightNumber(42L);
}
@@ -147,7 +143,7 @@ class XStreamMarshallerTests {
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamResult result = new StreamResult(os);
marshaller.marshal(flight, result);
String s = os.toString("UTF-8");
String s = new String(os.toByteArray(), "UTF-8");
assertThat(XmlContent.of(s)).isSimilarTo(EXPECTED_STRING);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2019 the original author 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.oxm.xstream;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@@ -30,7 +29,6 @@ import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
@@ -42,7 +40,6 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Arjen Poutsma
* @author Juergen Hoeller
*/
public class XStreamUnmarshallerTests {
@@ -50,16 +47,21 @@ public class XStreamUnmarshallerTests {
private XStreamMarshaller unmarshaller;
@BeforeEach
public void createUnmarshaller() {
public void createUnmarshaller() throws Exception {
unmarshaller = new XStreamMarshaller();
unmarshaller.setTypePermissions(AnyTypePermission.ANY);
Map<String, Class<?>> aliases = new HashMap<>();
aliases.put("flight", Flight.class);
unmarshaller.setAliases(aliases);
}
private void testFlight(Object o) {
boolean condition = o instanceof Flight;
assertThat(condition).as("Unmarshalled object is not Flights").isTrue();
Flight flight = (Flight) o;
assertThat(flight).as("Flight is null").isNotNull();
assertThat(flight.getFlightNumber()).as("Number is invalid").isEqualTo(42L);
}
@Test
public void unmarshalDomSource() throws Exception {
@@ -81,7 +83,7 @@ public class XStreamUnmarshallerTests {
@Test
public void unmarshalStreamSourceInputStream() throws Exception {
StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING.getBytes(StandardCharsets.UTF_8)));
StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING.getBytes("UTF-8")));
Object flights = unmarshaller.unmarshal(source);
testFlight(flights);
}
@@ -92,15 +94,5 @@ public class XStreamUnmarshallerTests {
Object flights = unmarshaller.unmarshal(source);
testFlight(flights);
}
private void testFlight(Object o) {
boolean condition = o instanceof Flight;
assertThat(condition).as("Unmarshalled object is not Flights").isTrue();
Flight flight = (Flight) o;
assertThat(flight).as("Flight is null").isNotNull();
assertThat(flight.getFlightNumber()).as("Number is invalid").isEqualTo(42L);
}
}

Some files were not shown because too many files have changed in this diff Show More