mirror of
https://github.com/spring-projects/spring-framework
synced 2026-06-08 17:33:33 +00:00
Compare commits
116 Commits
v5.2.16.RELEASE
...
5.2.x
| Author | SHA1 | Date | |
|---|---|---|---|
| b40e8e047c | |||
| a789e29a52 | |||
| e6d5b385f6 | |||
| c206866fed | |||
| ca01ee05f7 | |||
| 2e72269eb0 | |||
| ac82b5cd36 | |||
| 921635b3bc | |||
| 7c8fed7f3b | |||
| 89a3d64ada | |||
| a8bc09925d | |||
| e246b47f4d | |||
| 965a639275 | |||
| cbbb2871b3 | |||
| 18403cddea | |||
| ad191277a6 | |||
| b9b31afcc9 | |||
| 4542b53103 | |||
| 52c93b1c4b | |||
| 9c6cb744d4 | |||
| 1488b67712 | |||
| e163078a56 | |||
| 9f238c997d | |||
| 50177b1ad3 | |||
| 159a99bbaf | |||
| 41e158c93d | |||
| 833e750175 | |||
| d70054d686 | |||
| 36e4951b5e | |||
| 87b5080586 | |||
| 5cbf85a6f8 | |||
| 69c7eb9418 | |||
| fb763dd0f4 | |||
| 1b75f393a9 | |||
| 996f701a19 | |||
| 90cfde985e | |||
| 94f52bc94f | |||
| d4478bafa4 | |||
| 136e6db822 | |||
| 8f1f68377d | |||
| ce2367a76f | |||
| acf782347f | |||
| 1a03ffef62 | |||
| e954d7fc20 | |||
| ec13a3f1ba | |||
| 842f5b354d | |||
| 67a4b63d42 | |||
| 354dad615b | |||
| 0668323176 | |||
| e03e62c76a | |||
| 96a7fc693b | |||
| 50f6db2704 | |||
| 24ebb5ecd5 | |||
| a439a83f34 | |||
| f0de3a9924 | |||
| 17c3976bca | |||
| 9c4a33e64c | |||
| dd3ae4e63d | |||
| dfc435d045 | |||
| 78a24c0dd1 | |||
| 2bec54e7b3 | |||
| 52e2953de9 | |||
| 7b149a68c6 | |||
| d1b3b8eaf6 | |||
| f94794e5c0 | |||
| 26af506441 | |||
| b14a940716 | |||
| 4ecbf6511d | |||
| 5b6a32d1b9 | |||
| 263244f637 | |||
| 3a166ea742 | |||
| 6d4dfed772 | |||
| 09ef597836 | |||
| 50920e1a96 | |||
| 8c4d1d4d29 | |||
| 82f8d0dfd7 | |||
| 38f616a8e8 | |||
| 441c4d5d5c | |||
| 66f4d20fd4 | |||
| 2fa44d62b9 | |||
| c86ac97267 | |||
| fd916baf79 | |||
| 790d56dd18 | |||
| 5a5f118efc | |||
| edf664c1cf | |||
| 137bca129f | |||
| b01a3aeb6b | |||
| 195d375964 | |||
| ebd351753f | |||
| 9524ecd5b0 | |||
| 9053613a65 | |||
| 0aa7ba80e1 | |||
| 9a05a8846b | |||
| fb97a126a5 | |||
| 1ad5b4fbd6 | |||
| 4d1cdf6379 | |||
| e1ba3e7dbb | |||
| 2b55b9ccd5 | |||
| 90bcb2e375 | |||
| 9ad3464c80 | |||
| 1954a22c23 | |||
| bd90c4d0f0 | |||
| e31d66cd2b | |||
| eb349be1fc | |||
| 4b3e8619ec | |||
| 50d597eb41 | |||
| 9c931f669c | |||
| b7e6169e12 | |||
| 9c204dc475 | |||
| 21c0e50b33 | |||
| cecd2ee2e6 | |||
| 97a89d6db9 | |||
| 10a90d3204 | |||
| ab2a861163 | |||
| f56d6ea1fb | |||
| 420aa9bef0 |
@@ -23,6 +23,7 @@ buildSrc/build
|
||||
/spring-*/build
|
||||
/spring-core/kotlin-coroutines/build
|
||||
/framework-bom/build
|
||||
/framework-docs/build
|
||||
/integration-tests/build
|
||||
/src/asciidoc/build
|
||||
target/
|
||||
@@ -41,3 +42,5 @@ out
|
||||
test-output
|
||||
atlassian-ide-plugin.xml
|
||||
.gradletasknamecache
|
||||
|
||||
cached-antora-playbook.yml
|
||||
|
||||
+1
-1
@@ -8,4 +8,4 @@ wiki page.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please see https://pivotal.io/security.
|
||||
Please see https://spring.io/security-policy.
|
||||
|
||||
+9
-9
@@ -2,14 +2,14 @@ plugins {
|
||||
id 'io.spring.dependency-management' version '1.0.9.RELEASE' apply false
|
||||
id 'io.spring.ge.conventions' version '0.0.7'
|
||||
id 'io.spring.nohttp' version '0.0.5.RELEASE'
|
||||
id 'org.jetbrains.kotlin.jvm' version '1.3.72' apply false
|
||||
id "io.freefair.aspectj" version '4.1.6' apply false
|
||||
id 'org.jetbrains.dokka' version '0.10.1' apply false
|
||||
id 'org.jetbrains.kotlin.jvm' version '1.3.72' apply false
|
||||
id 'org.asciidoctor.jvm.convert' version '2.4.0'
|
||||
id 'org.asciidoctor.jvm.pdf' version '2.4.0'
|
||||
id 'de.undercouch.download' version '4.1.1'
|
||||
id "io.freefair.aspectj" version '4.1.6' apply false
|
||||
id "com.github.ben-manes.versions" version '0.28.0'
|
||||
id 'com.gradle.build-scan' version '3.2'
|
||||
id 'de.undercouch.download' version '4.1.1'
|
||||
}
|
||||
|
||||
apply from: "$rootDir/gradle/build-scan-user-data.gradle"
|
||||
@@ -28,7 +28,7 @@ configure(allprojects) { project ->
|
||||
imports {
|
||||
mavenBom "com.fasterxml.jackson:jackson-bom:2.10.5"
|
||||
mavenBom "io.netty:netty-bom:4.1.51.Final"
|
||||
mavenBom "io.projectreactor:reactor-bom:Dysprosium-SR21"
|
||||
mavenBom "io.projectreactor:reactor-bom:Dysprosium-SR25"
|
||||
mavenBom "io.rsocket:rsocket-bom:1.0.4"
|
||||
mavenBom "org.eclipse.jetty:jetty-bom:9.4.31.v20200723"
|
||||
mavenBom "org.jetbrains.kotlin:kotlin-bom:1.3.72"
|
||||
@@ -36,21 +36,21 @@ configure(allprojects) { project ->
|
||||
mavenBom "org.junit:junit-bom:5.6.3"
|
||||
}
|
||||
dependencies {
|
||||
dependencySet(group: 'org.apache.logging.log4j', version: '2.13.3') {
|
||||
dependencySet(group: 'org.apache.logging.log4j', version: '2.17.2') {
|
||||
entry 'log4j-api'
|
||||
entry 'log4j-core'
|
||||
entry 'log4j-jul'
|
||||
entry 'log4j-slf4j-impl'
|
||||
}
|
||||
dependency "org.slf4j:slf4j-api:1.7.30"
|
||||
dependency "org.slf4j:slf4j-api:1.7.32"
|
||||
dependency "com.google.code.findbugs:jsr305:3.0.2"
|
||||
|
||||
dependencySet(group: 'org.aspectj', version: '1.9.6') {
|
||||
dependencySet(group: 'org.aspectj', version: '1.9.7') {
|
||||
entry 'aspectjrt'
|
||||
entry 'aspectjtools'
|
||||
entry 'aspectjweaver'
|
||||
}
|
||||
dependencySet(group: 'org.codehaus.groovy', version: '2.5.13') {
|
||||
dependencySet(group: 'org.codehaus.groovy', version: '2.5.15') {
|
||||
entry 'groovy'
|
||||
entry 'groovy-jsr223'
|
||||
entry 'groovy-templates'
|
||||
@@ -61,7 +61,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.projectreactor.tools:blockhound:1.0.4.RELEASE"
|
||||
dependency "io.projectreactor.tools:blockhound:1.0.6.RELEASE"
|
||||
|
||||
dependency "com.caucho:hessian:4.0.63"
|
||||
dependency "com.fasterxml:aalto-xml:1.2.2"
|
||||
|
||||
@@ -4,7 +4,7 @@ changelog:
|
||||
- title: ":star: New Features"
|
||||
labels:
|
||||
- "type: enhancement"
|
||||
- title: ":beetle: Bug Fixes"
|
||||
- title: ":lady_beetle: Bug Fixes"
|
||||
labels:
|
||||
- "type: bug"
|
||||
- "type: regression"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:focal-20210119
|
||||
FROM ubuntu:focal-20220302
|
||||
|
||||
ADD setup.sh /setup.sh
|
||||
ADD get-jdk-url.sh /get-jdk-url.sh
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:focal-20210119
|
||||
FROM ubuntu:jammy-20230624
|
||||
|
||||
ADD setup.sh /setup.sh
|
||||
ADD get-jdk-url.sh /get-jdk-url.sh
|
||||
|
||||
@@ -3,10 +3,10 @@ set -e
|
||||
|
||||
case "$1" in
|
||||
java8)
|
||||
echo "https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u282-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u282b08.tar.gz"
|
||||
echo "https://github.com/bell-sw/Liberica/releases/download/8u372+7/bellsoft-jdk8u372+7-linux-amd64.tar.gz"
|
||||
;;
|
||||
java11)
|
||||
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"
|
||||
echo "https://github.com/bell-sw/Liberica/releases/download/11.0.19%2B7/bellsoft-jdk11.0.19+7-linux-amd64.tar.gz"
|
||||
;;
|
||||
*)
|
||||
echo $"Unknown java version"
|
||||
|
||||
+19
-6
@@ -2,7 +2,7 @@ anchors:
|
||||
git-repo-resource-source: &git-repo-resource-source
|
||||
uri: ((github-repo))
|
||||
username: ((github-username))
|
||||
password: ((github-password))
|
||||
password: ((github-ci-release-token))
|
||||
branch: ((branch))
|
||||
gradle-enterprise-task-params: &gradle-enterprise-task-params
|
||||
GRADLE_ENTERPRISE_ACCESS_KEY: ((gradle_enterprise_secret_access_key))
|
||||
@@ -26,7 +26,6 @@ anchors:
|
||||
docker-resource-source: &docker-resource-source
|
||||
username: ((docker-hub-username))
|
||||
password: ((docker-hub-password))
|
||||
tag: ((milestone))
|
||||
slack-fail-params: &slack-fail-params
|
||||
text: >
|
||||
:concourse-failed: <https://ci.spring.io/teams/${BUILD_TEAM_NAME}/pipelines/${BUILD_PIPELINE_NAME}/jobs/${BUILD_JOB_NAME}/builds/${BUILD_NAME}|${BUILD_PIPELINE_NAME} ${BUILD_JOB_NAME} failed!>
|
||||
@@ -44,19 +43,34 @@ anchors:
|
||||
GITHUB_TOKEN: ((github-ci-release-token))
|
||||
|
||||
resource_types:
|
||||
- name: registry-image
|
||||
type: registry-image
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: concourse/registry-image-resource
|
||||
tag: 1.7.1
|
||||
- name: artifactory-resource
|
||||
type: registry-image
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: springio/artifactory-resource
|
||||
tag: 0.0.13
|
||||
tag: 0.0.17
|
||||
- name: github-release
|
||||
type: registry-image
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: concourse/github-release-resource
|
||||
tag: 1.5.5
|
||||
- name: github-status-resource
|
||||
type: registry-image
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: dpb587/github-status-resource
|
||||
tag: master
|
||||
- name: slack-notification
|
||||
type: registry-image
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: cfcommunity/slack-notification-resource
|
||||
tag: latest
|
||||
resources:
|
||||
@@ -85,12 +99,14 @@ resources:
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: ((docker-hub-organization))/spring-framework-ci
|
||||
tag: ((milestone))
|
||||
- name: ci-image-jdk11
|
||||
type: docker-image
|
||||
icon: docker
|
||||
source:
|
||||
<<: *docker-resource-source
|
||||
repository: ((docker-hub-organization))/spring-framework-ci-jdk11
|
||||
tag: ((milestone))
|
||||
- name: artifactory-repo
|
||||
type: artifactory-resource
|
||||
icon: package-variant
|
||||
@@ -261,7 +277,6 @@ jobs:
|
||||
download_artifacts: false
|
||||
save_build_info: true
|
||||
- task: promote
|
||||
image: ci-image
|
||||
file: git-repo/ci/tasks/promote-version.yml
|
||||
params:
|
||||
RELEASE_TYPE: M
|
||||
@@ -306,7 +321,6 @@ jobs:
|
||||
download_artifacts: false
|
||||
save_build_info: true
|
||||
- task: promote
|
||||
image: ci-image
|
||||
file: git-repo/ci/tasks/promote-version.yml
|
||||
params:
|
||||
RELEASE_TYPE: RC
|
||||
@@ -351,7 +365,6 @@ jobs:
|
||||
download_artifacts: true
|
||||
save_build_info: true
|
||||
- task: promote
|
||||
image: ci-image
|
||||
file: git-repo/ci/tasks/promote-version.yml
|
||||
params:
|
||||
RELEASE_TYPE: RELEASE
|
||||
|
||||
@@ -6,11 +6,11 @@ CONFIG_DIR=git-repo/ci/config
|
||||
version=$( cat artifactory-repo/build-info.json | jq -r '.buildInfo.modules[0].id' | sed 's/.*:.*:\(.*\)/\1/' )
|
||||
export BUILD_INFO_LOCATION=$(pwd)/artifactory-repo/build-info.json
|
||||
|
||||
java -jar /opt/concourse-release-scripts.jar \
|
||||
java -jar /concourse-release-scripts.jar \
|
||||
--spring.config.location=${CONFIG_DIR}/release-scripts.yml \
|
||||
publishToCentral $RELEASE_TYPE $BUILD_INFO_LOCATION artifactory-repo || { exit 1; }
|
||||
|
||||
java -jar /opt/concourse-release-scripts.jar \
|
||||
java -jar /concourse-release-scripts.jar \
|
||||
--spring.config.location=${CONFIG_DIR}/release-scripts.yml \
|
||||
promote $RELEASE_TYPE $BUILD_INFO_LOCATION || { exit 1; }
|
||||
|
||||
|
||||
@@ -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 Buildmaster" > /dev/null
|
||||
git config user.email "buildmaster@springframework.org" > /dev/null
|
||||
git config user.name "Spring Builds" > /dev/null
|
||||
git config user.email "spring-builds@users.noreply.github.com" > /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
|
||||
|
||||
@@ -4,7 +4,9 @@ image_resource:
|
||||
type: registry-image
|
||||
source:
|
||||
repository: springio/github-changelog-generator
|
||||
tag: '0.0.6'
|
||||
tag: '0.0.8'
|
||||
username: ((docker-hub-username))
|
||||
password: ((docker-hub-password))
|
||||
inputs:
|
||||
- name: git-repo
|
||||
- name: artifactory-repo
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
---
|
||||
platform: linux
|
||||
image_resource:
|
||||
type: registry-image
|
||||
source:
|
||||
repository: springio/concourse-release-scripts
|
||||
tag: '0.3.4'
|
||||
username: ((docker-hub-username))
|
||||
password: ((docker-hub-password))
|
||||
inputs:
|
||||
- name: git-repo
|
||||
- name: artifactory-repo
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
version=5.2.16.BUILD-SNAPSHOT
|
||||
version=5.2.26.BUILD-SNAPSHOT
|
||||
org.gradle.jvmargs=-Xmx1536M
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
|
||||
+3
-4
@@ -3,7 +3,7 @@ configurations {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
asciidoctorExt("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.4.0.RELEASE")
|
||||
asciidoctorExt("io.spring.asciidoctor:spring-asciidoctor-extensions-block-switch:0.6.1")
|
||||
}
|
||||
|
||||
repositories {
|
||||
@@ -107,9 +107,8 @@ dokka {
|
||||
}
|
||||
|
||||
task downloadResources(type: Download) {
|
||||
def version = "0.2.1.RELEASE"
|
||||
src "https://repo.spring.io/release/io/spring/docresources/" +
|
||||
"spring-doc-resources/$version/spring-doc-resources-${version}.zip"
|
||||
src "https://repo.spring.io/artifactory/snapshot/io/spring/docresources/" +
|
||||
"spring-doc-resources/0.2.6-SNAPSHOT/spring-doc-resources-0.2.6-20210308.231804-2.zip"
|
||||
dest project.file("$buildDir/docs/spring-doc-resources.zip")
|
||||
onlyIfModified true
|
||||
useETag "all"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
* 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.
|
||||
@@ -23,7 +23,7 @@ import java.lang.reflect.AccessibleObject;
|
||||
* terminology).
|
||||
*
|
||||
* <p>A runtime joinpoint is an <i>event</i> that occurs on a static
|
||||
* joinpoint (i.e. a location in a the program). For instance, an
|
||||
* joinpoint (i.e. a location in a 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.
|
||||
|
||||
+5
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -103,10 +103,11 @@ 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
|
||||
if (aspectClass.getSuperclass().getAnnotation(Aspect.class) != null &&
|
||||
!Modifier.isAbstract(aspectClass.getSuperclass().getModifiers())) {
|
||||
Class<?> superclass = aspectClass.getSuperclass();
|
||||
if (superclass.getAnnotation(Aspect.class) != null &&
|
||||
!Modifier.isAbstract(superclass.getModifiers())) {
|
||||
throw new AopConfigException("[" + aspectClass.getName() + "] cannot extend concrete aspect [" +
|
||||
aspectClass.getSuperclass().getName() + "]");
|
||||
superclass.getName() + "]");
|
||||
}
|
||||
|
||||
AjType<?> ajType = AjTypeSystem.getAjType(aspectClass);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -237,7 +237,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
* validates it if not.
|
||||
*/
|
||||
private void validateClassIfNecessary(Class<?> proxySuperClass, @Nullable ClassLoader proxyClassLoader) {
|
||||
if (logger.isWarnEnabled()) {
|
||||
if (logger.isInfoEnabled()) {
|
||||
synchronized (validatedClasses) {
|
||||
if (!validatedClasses.containsKey(proxySuperClass)) {
|
||||
doValidateClass(proxySuperClass, proxyClassLoader,
|
||||
@@ -375,6 +375,22 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the given method with a CGLIB MethodProxy if possible, falling back
|
||||
* to a plain reflection invocation in case of a fast-class generation failure.
|
||||
*/
|
||||
@Nullable
|
||||
private static Object invokeMethod(@Nullable Object target, Method method, Object[] args, MethodProxy methodProxy)
|
||||
throws Throwable {
|
||||
try {
|
||||
return methodProxy.invoke(target, args);
|
||||
}
|
||||
catch (CodeGenerationException ex) {
|
||||
CglibMethodInvocation.logFastClassGenerationFailure(method);
|
||||
return AopUtils.invokeJoinpointUsingReflection(target, method, args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a return value. Wraps a return of {@code this} if necessary to be the
|
||||
* {@code proxy} and also verifies that {@code null} is not returned as a primitive.
|
||||
@@ -425,7 +441,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
@Override
|
||||
@Nullable
|
||||
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
|
||||
Object retVal = methodProxy.invoke(this.target, args);
|
||||
Object retVal = invokeMethod(this.target, method, args, methodProxy);
|
||||
return processReturnType(proxy, this.target, method, retVal);
|
||||
}
|
||||
}
|
||||
@@ -450,7 +466,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
Object oldProxy = null;
|
||||
try {
|
||||
oldProxy = AopContext.setCurrentProxy(proxy);
|
||||
Object retVal = methodProxy.invoke(this.target, args);
|
||||
Object retVal = invokeMethod(this.target, method, args, methodProxy);
|
||||
return processReturnType(proxy, this.target, method, retVal);
|
||||
}
|
||||
finally {
|
||||
@@ -478,7 +494,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
|
||||
Object target = this.targetSource.getTarget();
|
||||
try {
|
||||
Object retVal = methodProxy.invoke(target, args);
|
||||
Object retVal = invokeMethod(target, method, args, methodProxy);
|
||||
return processReturnType(proxy, target, method, retVal);
|
||||
}
|
||||
finally {
|
||||
@@ -508,7 +524,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
Object target = this.targetSource.getTarget();
|
||||
try {
|
||||
oldProxy = AopContext.setCurrentProxy(proxy);
|
||||
Object retVal = methodProxy.invoke(target, args);
|
||||
Object retVal = invokeMethod(target, method, args, methodProxy);
|
||||
return processReturnType(proxy, target, method, retVal);
|
||||
}
|
||||
finally {
|
||||
@@ -679,13 +695,13 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
Object retVal;
|
||||
// Check whether we only have one InvokerInterceptor: that is,
|
||||
// no real advice, but just reflective invocation of the target.
|
||||
if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
|
||||
if (chain.isEmpty() && CglibMethodInvocation.isMethodProxyCompatible(method)) {
|
||||
// We can skip creating a MethodInvocation: just invoke the target directly.
|
||||
// Note that the final invoker must be an InvokerInterceptor, so we know
|
||||
// it does nothing but a reflective operation on the target, and no hot
|
||||
// swapping or fancy proxying.
|
||||
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
|
||||
retVal = methodProxy.invoke(target, argsToUse);
|
||||
retVal = invokeMethod(target, method, argsToUse, methodProxy);
|
||||
}
|
||||
else {
|
||||
// We need to create a method invocation...
|
||||
@@ -737,10 +753,7 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers);
|
||||
|
||||
// Only use method proxy for public methods not derived from java.lang.Object
|
||||
this.methodProxy = (Modifier.isPublic(method.getModifiers()) &&
|
||||
method.getDeclaringClass() != Object.class && !AopUtils.isEqualsMethod(method) &&
|
||||
!AopUtils.isHashCodeMethod(method) && !AopUtils.isToStringMethod(method) ?
|
||||
methodProxy : null);
|
||||
this.methodProxy = (isMethodProxyCompatible(method) ? methodProxy : null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -776,10 +789,25 @@ class CglibAopProxy implements AopProxy, Serializable {
|
||||
@Override
|
||||
protected Object invokeJoinpoint() throws Throwable {
|
||||
if (this.methodProxy != null) {
|
||||
return this.methodProxy.invoke(this.target, this.arguments);
|
||||
try {
|
||||
return this.methodProxy.invoke(this.target, this.arguments);
|
||||
}
|
||||
catch (CodeGenerationException ex) {
|
||||
logFastClassGenerationFailure(this.method);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return super.invokeJoinpoint();
|
||||
return super.invokeJoinpoint();
|
||||
}
|
||||
|
||||
static boolean isMethodProxyCompatible(Method method) {
|
||||
return (Modifier.isPublic(method.getModifiers()) &&
|
||||
method.getDeclaringClass() != Object.class && !AopUtils.isEqualsMethod(method) &&
|
||||
!AopUtils.isHashCodeMethod(method) && !AopUtils.isToStringMethod(method));
|
||||
}
|
||||
|
||||
static void logFastClassGenerationFailure(Method method) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Failed to generate CGLIB fast class for method: " + method);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
* 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.
|
||||
@@ -43,9 +43,11 @@ import org.springframework.aop.SpringProxy;
|
||||
* @see AdvisedSupport#setProxyTargetClass
|
||||
* @see AdvisedSupport#setInterfaces
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 7930414337282325166L;
|
||||
|
||||
|
||||
@Override
|
||||
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
|
||||
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -421,11 +421,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
|
||||
* are unaffected by such changes.
|
||||
*/
|
||||
private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {
|
||||
if (this.advisorChainInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ObjectUtils.isEmpty(this.interceptorNames)) {
|
||||
if (!this.advisorChainInitialized && !ObjectUtils.isEmpty(this.interceptorNames)) {
|
||||
if (this.beanFactory == null) {
|
||||
throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
|
||||
"- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
|
||||
@@ -464,9 +460,9 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
|
||||
addAdvisorOnChainCreation(advice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.advisorChainInitialized = true;
|
||||
this.advisorChainInitialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+8
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2014 the original author or authors.
|
||||
* 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.
|
||||
@@ -22,13 +22,18 @@ import org.springframework.contextsupport.testfixture.jcache.AbstractJCacheAnnot
|
||||
|
||||
/**
|
||||
* @author Stephane Nicoll
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class JCacheAspectJNamespaceConfigTests extends AbstractJCacheAnnotationTests {
|
||||
|
||||
@Override
|
||||
protected ApplicationContext getApplicationContext() {
|
||||
return new GenericXmlApplicationContext(
|
||||
"/org/springframework/cache/config/annotation-jcache-aspectj.xml");
|
||||
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
|
||||
// Disallow bean definition overriding to test https://github.com/spring-projects/spring-framework/pull/27499
|
||||
context.setAllowBeanDefinitionOverriding(false);
|
||||
context.load("/org/springframework/cache/config/annotation-jcache-aspectj.xml");
|
||||
context.refresh();
|
||||
return context;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -83,7 +83,10 @@ 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, (long) 0);
|
||||
values.put(long.class, 0L);
|
||||
values.put(float.class, 0F);
|
||||
values.put(double.class, 0D);
|
||||
values.put(char.class, '\0');
|
||||
DEFAULT_TYPE_VALUES = Collections.unmodifiableMap(values);
|
||||
}
|
||||
|
||||
|
||||
+24
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* Copyright 2002-2022 the original author 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.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.net.URL;
|
||||
import java.security.ProtectionDomain;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -281,9 +283,17 @@ public final class CachedIntrospectionResults {
|
||||
// This call is slow so we do it once.
|
||||
PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
|
||||
for (PropertyDescriptor pd : pds) {
|
||||
if (Class.class == beanClass &&
|
||||
("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
|
||||
// Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
|
||||
if (Class.class == beanClass && !("name".equals(pd.getName()) ||
|
||||
(pd.getName().endsWith("Name") && String.class == pd.getPropertyType()))) {
|
||||
// Only allow all name variants of Class properties
|
||||
continue;
|
||||
}
|
||||
if (URL.class == beanClass && "content".equals(pd.getName())) {
|
||||
// Only allow URL attribute introspection, not content resolution
|
||||
continue;
|
||||
}
|
||||
if (pd.getWriteMethod() == null && isInvalidReadOnlyPropertyType(pd.getPropertyType())) {
|
||||
// Ignore read-only properties such as ClassLoader - no need to bind to those
|
||||
continue;
|
||||
}
|
||||
if (logger.isTraceEnabled()) {
|
||||
@@ -321,6 +331,10 @@ public final class CachedIntrospectionResults {
|
||||
// GenericTypeAwarePropertyDescriptor leniently resolves a set* write method
|
||||
// against a declared read method, so we prefer read method descriptors here.
|
||||
pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
|
||||
if (pd.getWriteMethod() == null && isInvalidReadOnlyPropertyType(pd.getPropertyType())) {
|
||||
// Ignore read-only properties such as ClassLoader - no need to bind to those
|
||||
continue;
|
||||
}
|
||||
this.propertyDescriptors.put(pd.getName(), pd);
|
||||
}
|
||||
}
|
||||
@@ -329,6 +343,12 @@ public final class CachedIntrospectionResults {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isInvalidReadOnlyPropertyType(@Nullable Class<?> returnType) {
|
||||
return (returnType != null && (AutoCloseable.class.isAssignableFrom(returnType) ||
|
||||
ClassLoader.class.isAssignableFrom(returnType) ||
|
||||
ProtectionDomain.class.isAssignableFrom(returnType)));
|
||||
}
|
||||
|
||||
|
||||
BeanInfo getBeanInfo() {
|
||||
return this.beanInfo;
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -138,7 +138,7 @@ final class GenericTypeAwarePropertyDescriptor extends PropertyDescriptor {
|
||||
Set<Method> ambiguousCandidates = this.ambiguousWriteMethods;
|
||||
if (ambiguousCandidates != null) {
|
||||
this.ambiguousWriteMethods = null;
|
||||
LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class).warn("Invalid JavaBean property '" +
|
||||
LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class).debug("Non-unique JavaBean property '" +
|
||||
getName() + "' being accessed! Ambiguous write methods found next to actually used [" +
|
||||
this.writeMethod + "]: " + ambiguousCandidates);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,8 +23,9 @@ import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* Common interface for classes that can access named properties
|
||||
* (such as bean properties of an object or fields in an object)
|
||||
* Serves as base interface for {@link BeanWrapper}.
|
||||
* (such as bean properties of an object or fields in an object).
|
||||
*
|
||||
* <p>Serves as base interface for {@link BeanWrapper}.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.1
|
||||
|
||||
+1
-1
@@ -459,7 +459,7 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
|
||||
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
|
||||
if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
|
||||
return InjectionMetadata.EMPTY;
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -351,7 +351,9 @@ 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) {
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -350,7 +350,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
|
||||
else {
|
||||
String scopeName = mbd.getScope();
|
||||
if (!StringUtils.hasLength(scopeName)) {
|
||||
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
|
||||
throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
|
||||
}
|
||||
Scope scope = this.scopes.get(scopeName);
|
||||
if (scope == null) {
|
||||
|
||||
+11
-5
@@ -62,6 +62,8 @@ import org.springframework.util.StringUtils;
|
||||
@SuppressWarnings("serial")
|
||||
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
|
||||
|
||||
private static final String DESTROY_METHOD_NAME = "destroy";
|
||||
|
||||
private static final String CLOSE_METHOD_NAME = "close";
|
||||
|
||||
private static final String SHUTDOWN_METHOD_NAME = "shutdown";
|
||||
@@ -104,13 +106,16 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
|
||||
Assert.notNull(bean, "Disposable bean must not be null");
|
||||
this.bean = bean;
|
||||
this.beanName = beanName;
|
||||
this.invokeDisposableBean =
|
||||
(this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
|
||||
this.invokeDisposableBean = (bean instanceof DisposableBean &&
|
||||
!beanDefinition.isExternallyManagedDestroyMethod(DESTROY_METHOD_NAME));
|
||||
this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
|
||||
this.acc = acc;
|
||||
|
||||
String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
|
||||
if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
|
||||
if (destroyMethodName != null &&
|
||||
!(this.invokeDisposableBean && DESTROY_METHOD_NAME.equals(destroyMethodName)) &&
|
||||
!beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
|
||||
|
||||
this.destroyMethodName = destroyMethodName;
|
||||
Method destroyMethod = determineDestroyMethod(destroyMethodName);
|
||||
if (destroyMethod == null) {
|
||||
@@ -135,6 +140,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
|
||||
}
|
||||
this.destroyMethod = destroyMethod;
|
||||
}
|
||||
|
||||
this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
|
||||
}
|
||||
|
||||
@@ -349,8 +355,8 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
|
||||
destroyMethodName = beanDefinition.getDestroyMethodName();
|
||||
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
|
||||
(destroyMethodName == null && bean instanceof AutoCloseable)) {
|
||||
// Only perform destroy method inference or Closeable detection
|
||||
// in case of the bean not explicitly implementing DisposableBean
|
||||
// Only perform destroy method inference in case of the bean
|
||||
// not explicitly implementing the DisposableBean interface
|
||||
destroyMethodName = null;
|
||||
if (!(bean instanceof DisposableBean)) {
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -64,24 +64,24 @@ public final class ParserContext {
|
||||
}
|
||||
|
||||
|
||||
public final XmlReaderContext getReaderContext() {
|
||||
public XmlReaderContext getReaderContext() {
|
||||
return this.readerContext;
|
||||
}
|
||||
|
||||
public final BeanDefinitionRegistry getRegistry() {
|
||||
public BeanDefinitionRegistry getRegistry() {
|
||||
return this.readerContext.getRegistry();
|
||||
}
|
||||
|
||||
public final BeanDefinitionParserDelegate getDelegate() {
|
||||
public BeanDefinitionParserDelegate getDelegate() {
|
||||
return this.delegate;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public final BeanDefinition getContainingBeanDefinition() {
|
||||
public BeanDefinition getContainingBeanDefinition() {
|
||||
return this.containingBeanDefinition;
|
||||
}
|
||||
|
||||
public final boolean isNested() {
|
||||
public boolean isNested() {
|
||||
return (this.containingBeanDefinition != null);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ 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}.
|
||||
@@ -80,19 +81,43 @@ class BeanUtilsTests {
|
||||
}
|
||||
|
||||
@Test // gh-22531
|
||||
void testInstantiateClassWithOptionalPrimitiveType() 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");
|
||||
void instantiateClassWithFewerArgsThanParameters() throws NoSuchMethodException {
|
||||
Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor();
|
||||
|
||||
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() ->
|
||||
BeanUtils.instantiateClass(constructor, null, null, "foo"));
|
||||
}
|
||||
|
||||
@Test // gh-22531
|
||||
void testInstantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException {
|
||||
Constructor<BeanWithPrimitiveTypes> ctor = BeanWithPrimitiveTypes.class.getDeclaredConstructor(int.class, boolean.class, String.class);
|
||||
@Test // gh-22531
|
||||
void instantiateClassWithMoreArgsThanParameters() throws NoSuchMethodException {
|
||||
Constructor<BeanWithPrimitiveTypes> constructor = getBeanWithPrimitiveTypesConstructor();
|
||||
|
||||
assertThatExceptionOfType(BeanInstantiationException.class).isThrownBy(() ->
|
||||
BeanUtils.instantiateClass(ctor, null, null, "foo", null));
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -535,30 +560,68 @@ class BeanUtilsTests {
|
||||
|
||||
private static class BeanWithPrimitiveTypes {
|
||||
|
||||
private int counter;
|
||||
|
||||
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 String value;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public BeanWithPrimitiveTypes(int counter, boolean flag, String value) {
|
||||
this.counter = counter;
|
||||
this.flag = flag;
|
||||
this.value = value;
|
||||
}
|
||||
public BeanWithPrimitiveTypes(boolean flag, byte byteCount, short shortCount, int intCount, long longCount,
|
||||
float floatCount, double doubleCount, char character, String text) {
|
||||
|
||||
public int getCounter() {
|
||||
return 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;
|
||||
}
|
||||
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
public byte getByteCount() {
|
||||
return byteCount;
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ public class BeanWrapperAutoGrowingTests {
|
||||
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
public void setup() {
|
||||
wrapper.setAutoGrowNestedPaths(true);
|
||||
}
|
||||
|
||||
|
||||
+28
-36
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -16,7 +16,6 @@
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -86,7 +85,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericList() throws MalformedURLException {
|
||||
public void testGenericList() throws Exception {
|
||||
GenericBean<?> gb = new GenericBean<>();
|
||||
BeanWrapper bw = new BeanWrapperImpl(gb);
|
||||
List<String> input = new ArrayList<>();
|
||||
@@ -98,7 +97,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListElement() throws MalformedURLException {
|
||||
public void testGenericListElement() throws Exception {
|
||||
GenericBean<?> gb = new GenericBean<>();
|
||||
gb.setResourceList(new ArrayList<>());
|
||||
BeanWrapper bw = new BeanWrapperImpl(gb);
|
||||
@@ -163,10 +162,8 @@ public class BeanWrapperGenericsTests {
|
||||
value2.add(Boolean.TRUE);
|
||||
input.put("2", value2);
|
||||
bw.setPropertyValue("collectionMap", input);
|
||||
boolean condition1 = gb.getCollectionMap().get(1) instanceof HashSet;
|
||||
assertThat(condition1).isTrue();
|
||||
boolean condition = gb.getCollectionMap().get(2) instanceof ArrayList;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue();
|
||||
assertThat(gb.getCollectionMap().get(2) instanceof ArrayList).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -178,8 +175,7 @@ public class BeanWrapperGenericsTests {
|
||||
HashSet<Integer> value1 = new HashSet<>();
|
||||
value1.add(1);
|
||||
bw.setPropertyValue("collectionMap[1]", value1);
|
||||
boolean condition = gb.getCollectionMap().get(1) instanceof HashSet;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(gb.getCollectionMap().get(1) instanceof HashSet).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -195,7 +191,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfLists() throws MalformedURLException {
|
||||
public void testGenericListOfLists() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
List<List<Integer>> list = new LinkedList<>();
|
||||
list.add(new LinkedList<>());
|
||||
@@ -207,7 +203,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfListsWithElementConversion() throws MalformedURLException {
|
||||
public void testGenericListOfListsWithElementConversion() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
List<List<Integer>> list = new LinkedList<>();
|
||||
list.add(new LinkedList<>());
|
||||
@@ -219,7 +215,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfArrays() throws MalformedURLException {
|
||||
public void testGenericListOfArrays() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
ArrayList<String[]> list = new ArrayList<>();
|
||||
list.add(new String[] {"str1", "str2"});
|
||||
@@ -231,7 +227,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfArraysWithElementConversion() throws MalformedURLException {
|
||||
public void testGenericListOfArraysWithElementConversion() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
ArrayList<String[]> list = new ArrayList<>();
|
||||
list.add(new String[] {"str1", "str2"});
|
||||
@@ -244,7 +240,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfMaps() throws MalformedURLException {
|
||||
public void testGenericListOfMaps() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
List<Map<Integer, Long>> list = new LinkedList<>();
|
||||
list.add(new HashMap<>());
|
||||
@@ -256,7 +252,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericListOfMapsWithElementConversion() throws MalformedURLException {
|
||||
public void testGenericListOfMapsWithElementConversion() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
List<Map<Integer, Long>> list = new LinkedList<>();
|
||||
list.add(new HashMap<>());
|
||||
@@ -268,7 +264,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericMapOfMaps() throws MalformedURLException {
|
||||
public void testGenericMapOfMaps() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
Map<String, Map<Integer, Long>> map = new HashMap<>();
|
||||
map.put("mykey", new HashMap<>());
|
||||
@@ -280,7 +276,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericMapOfMapsWithElementConversion() throws MalformedURLException {
|
||||
public void testGenericMapOfMapsWithElementConversion() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
Map<String, Map<Integer, Long>> map = new HashMap<>();
|
||||
map.put("mykey", new HashMap<>());
|
||||
@@ -292,7 +288,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericMapOfLists() throws MalformedURLException {
|
||||
public void testGenericMapOfLists() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
Map<Integer, List<Integer>> map = new HashMap<>();
|
||||
map.put(1, new LinkedList<>());
|
||||
@@ -304,7 +300,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericMapOfListsWithElementConversion() throws MalformedURLException {
|
||||
public void testGenericMapOfListsWithElementConversion() {
|
||||
GenericBean<String> gb = new GenericBean<>();
|
||||
Map<Integer, List<Integer>> map = new HashMap<>();
|
||||
map.put(1, new LinkedList<>());
|
||||
@@ -316,7 +312,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericTypeNestingMapOfInteger() throws Exception {
|
||||
public void testGenericTypeNestingMapOfInteger() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("testKey", "100");
|
||||
|
||||
@@ -325,14 +321,13 @@ public class BeanWrapperGenericsTests {
|
||||
bw.setPropertyValue("mapOfInteger", map);
|
||||
|
||||
Object obj = gb.getMapOfInteger().get("testKey");
|
||||
boolean condition = obj instanceof Integer;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(obj instanceof Integer).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericTypeNestingMapOfListOfInteger() throws Exception {
|
||||
public void testGenericTypeNestingMapOfListOfInteger() {
|
||||
Map<String, List<String>> map = new HashMap<>();
|
||||
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
map.put("testKey", list);
|
||||
|
||||
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
|
||||
@@ -340,13 +335,12 @@ public class BeanWrapperGenericsTests {
|
||||
bw.setPropertyValue("mapOfListOfInteger", map);
|
||||
|
||||
Object obj = gb.getMapOfListOfInteger().get("testKey").get(0);
|
||||
boolean condition = obj instanceof Integer;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(obj instanceof Integer).isTrue();
|
||||
assertThat(((Integer) obj).intValue()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericTypeNestingListOfMapOfInteger() throws Exception {
|
||||
public void testGenericTypeNestingListOfMapOfInteger() {
|
||||
List<Map<String, String>> list = new LinkedList<>();
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("testKey", "5");
|
||||
@@ -357,15 +351,14 @@ public class BeanWrapperGenericsTests {
|
||||
bw.setPropertyValue("listOfMapOfInteger", list);
|
||||
|
||||
Object obj = gb.getListOfMapOfInteger().get(0).get("testKey");
|
||||
boolean condition = obj instanceof Integer;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(obj instanceof Integer).isTrue();
|
||||
assertThat(((Integer) obj).intValue()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception {
|
||||
public void testGenericTypeNestingMapOfListOfListOfInteger() {
|
||||
Map<String, List<List<String>>> map = new HashMap<>();
|
||||
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
map.put("testKey", Collections.singletonList(list));
|
||||
|
||||
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
|
||||
@@ -373,8 +366,7 @@ public class BeanWrapperGenericsTests {
|
||||
bw.setPropertyValue("mapOfListOfListOfInteger", map);
|
||||
|
||||
Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
|
||||
boolean condition = obj instanceof Integer;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(obj instanceof Integer).isTrue();
|
||||
assertThat(((Integer) obj).intValue()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@@ -465,7 +457,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericallyTypedIntegerBean() throws Exception {
|
||||
public void testGenericallyTypedIntegerBean() {
|
||||
GenericIntegerBean gb = new GenericIntegerBean();
|
||||
BeanWrapper bw = new BeanWrapperImpl(gb);
|
||||
bw.setPropertyValue("genericProperty", "10");
|
||||
@@ -476,7 +468,7 @@ public class BeanWrapperGenericsTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenericallyTypedSetOfIntegerBean() throws Exception {
|
||||
public void testGenericallyTypedSetOfIntegerBean() {
|
||||
GenericSetOfIntegerBean gb = new GenericSetOfIntegerBean();
|
||||
BeanWrapper bw = new BeanWrapperImpl(gb);
|
||||
bw.setPropertyValue("genericProperty", "10");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,6 +23,9 @@ import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.testfixture.beans.TestBean;
|
||||
import org.springframework.core.OverridingClassLoader;
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
@@ -104,7 +107,7 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
|
||||
.satisfies(ex -> assertThat(ex.getPossibleMatches()).containsExactly("age"));
|
||||
}
|
||||
|
||||
@Test // Can't be shared; there is no such thing as a read-only field
|
||||
@Test // Can't be shared; there is no such thing as a read-only field
|
||||
public void setReadOnlyMapProperty() {
|
||||
TypedReadOnlyMap map = new TypedReadOnlyMap(Collections.singletonMap("key", new TestBean()));
|
||||
TypedReadOnlyMapClient target = new TypedReadOnlyMapClient();
|
||||
@@ -150,18 +153,58 @@ public class BeanWrapperTests extends AbstractPropertyAccessorTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void propertyDescriptors() {
|
||||
public void propertyDescriptors() throws Exception {
|
||||
TestBean target = new TestBean();
|
||||
target.setSpouse(new TestBean());
|
||||
BeanWrapper accessor = createAccessor(target);
|
||||
accessor.setPropertyValue("name", "a");
|
||||
accessor.setPropertyValue("spouse.name", "b");
|
||||
|
||||
assertThat(target.getName()).isEqualTo("a");
|
||||
assertThat(target.getSpouse().getName()).isEqualTo("b");
|
||||
assertThat(accessor.getPropertyValue("name")).isEqualTo("a");
|
||||
assertThat(accessor.getPropertyValue("spouse.name")).isEqualTo("b");
|
||||
assertThat(accessor.getPropertyDescriptor("name").getPropertyType()).isEqualTo(String.class);
|
||||
assertThat(accessor.getPropertyDescriptor("spouse.name").getPropertyType()).isEqualTo(String.class);
|
||||
|
||||
assertThat(accessor.isReadableProperty("class.package")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.module")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.classLoader")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.name")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("class.simpleName")).isTrue();
|
||||
assertThat(accessor.getPropertyValue("class.name")).isEqualTo(TestBean.class.getName());
|
||||
assertThat(accessor.getPropertyValue("class.simpleName")).isEqualTo(TestBean.class.getSimpleName());
|
||||
assertThat(accessor.getPropertyDescriptor("class.name").getPropertyType()).isEqualTo(String.class);
|
||||
assertThat(accessor.getPropertyDescriptor("class.simpleName").getPropertyType()).isEqualTo(String.class);
|
||||
|
||||
accessor = createAccessor(new DefaultResourceLoader());
|
||||
|
||||
assertThat(accessor.isReadableProperty("class.package")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.module")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.classLoader")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.name")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("class.simpleName")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("classLoader")).isTrue();
|
||||
assertThat(accessor.isWritableProperty("classLoader")).isTrue();
|
||||
OverridingClassLoader ocl = new OverridingClassLoader(getClass().getClassLoader());
|
||||
accessor.setPropertyValue("classLoader", ocl);
|
||||
assertThat(accessor.getPropertyValue("classLoader")).isSameAs(ocl);
|
||||
|
||||
accessor = createAccessor(new UrlResource("https://spring.io"));
|
||||
|
||||
assertThat(accessor.isReadableProperty("class.package")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.module")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.classLoader")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("class.name")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("class.simpleName")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("URL.protocol")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("URL.host")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("URL.port")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("URL.file")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("URL.content")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("inputStream")).isFalse();
|
||||
assertThat(accessor.isReadableProperty("filename")).isTrue();
|
||||
assertThat(accessor.isReadableProperty("description")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -22,7 +22,8 @@ import javax.lang.model.element.Element;
|
||||
|
||||
/**
|
||||
* Provide the list of stereotypes that match an {@link Element}.
|
||||
* If an element has one more stereotypes, it is referenced in the index
|
||||
*
|
||||
* <p>If an element has one or more stereotypes, it is referenced in the index
|
||||
* of candidate components and each stereotype can be queried individually.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
|
||||
+3
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -58,6 +58,8 @@ import org.springframework.lang.Nullable;
|
||||
* @since 1.1
|
||||
* @see SchedulerFactoryBean#setDataSource
|
||||
* @see SchedulerFactoryBean#setNonTransactionalDataSource
|
||||
* @see SchedulerFactoryBean#getConfigTimeDataSource()
|
||||
* @see SchedulerFactoryBean#getConfigTimeNonTransactionalDataSource()
|
||||
* @see org.springframework.jdbc.datasource.DataSourceUtils#doGetConnection
|
||||
* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
|
||||
*/
|
||||
|
||||
+2
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -313,6 +313,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe
|
||||
* If set, this will override corresponding settings in Quartz properties.
|
||||
* <p>Note: If this is set, the Quartz settings should not define
|
||||
* a job store "dataSource" to avoid meaningless double configuration.
|
||||
* Also, do not define a "org.quartz.jobStore.class" property at all.
|
||||
* <p>A Spring-specific subclass of Quartz' JobStoreCMT will be used.
|
||||
* It is therefore strongly recommended to perform all operations on
|
||||
* the Scheduler within Spring-managed (or plain JTA) transactions.
|
||||
|
||||
@@ -34,8 +34,8 @@ dependencies {
|
||||
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")
|
||||
testCompile("javax.inject:javax.inject-tck")
|
||||
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)
|
||||
|
||||
+15
-11
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -244,17 +244,21 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
|
||||
|
||||
private static void registerCacheAspect(Element element, ParserContext parserContext) {
|
||||
if (!parserContext.getRegistry().containsBeanDefinition(CacheManagementConfigUtils.JCACHE_ASPECT_BEAN_NAME)) {
|
||||
Object eleSource = parserContext.extractSource(element);
|
||||
RootBeanDefinition def = new RootBeanDefinition();
|
||||
def.setBeanClassName(JCACHE_ASPECT_CLASS_NAME);
|
||||
def.setFactoryMethodName("aspectOf");
|
||||
BeanDefinition sourceDef = createJCacheOperationSourceBeanDefinition(element, eleSource);
|
||||
String sourceName =
|
||||
parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
|
||||
def.getPropertyValues().add("cacheOperationSource", new RuntimeBeanReference(sourceName));
|
||||
Object source = parserContext.extractSource(element);
|
||||
|
||||
parserContext.registerBeanComponent(new BeanComponentDefinition(sourceDef, sourceName));
|
||||
parserContext.registerBeanComponent(new BeanComponentDefinition(def, CacheManagementConfigUtils.JCACHE_ASPECT_BEAN_NAME));
|
||||
BeanDefinition cacheOperationSourceDef = createJCacheOperationSourceBeanDefinition(element, source);
|
||||
String cacheOperationSourceName = parserContext.getReaderContext().registerWithGeneratedName(cacheOperationSourceDef);
|
||||
|
||||
RootBeanDefinition jcacheAspectDef = new RootBeanDefinition();
|
||||
jcacheAspectDef.setBeanClassName(JCACHE_ASPECT_CLASS_NAME);
|
||||
jcacheAspectDef.setFactoryMethodName("aspectOf");
|
||||
jcacheAspectDef.getPropertyValues().add("cacheOperationSource", new RuntimeBeanReference(cacheOperationSourceName));
|
||||
parserContext.getRegistry().registerBeanDefinition(CacheManagementConfigUtils.JCACHE_ASPECT_BEAN_NAME, jcacheAspectDef);
|
||||
|
||||
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);
|
||||
compositeDef.addNestedComponent(new BeanComponentDefinition(cacheOperationSourceDef, cacheOperationSourceName));
|
||||
compositeDef.addNestedComponent(new BeanComponentDefinition(jcacheAspectDef, CacheManagementConfigUtils.JCACHE_ASPECT_BEAN_NAME));
|
||||
parserContext.registerComponent(compositeDef);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
-27
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -16,11 +16,12 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -93,9 +94,9 @@ public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
|
||||
|
||||
private String resourcePattern = DEFAULT_RESOURCE_PATTERN;
|
||||
|
||||
private final List<TypeFilter> includeFilters = new LinkedList<>();
|
||||
private final List<TypeFilter> includeFilters = new ArrayList<>();
|
||||
|
||||
private final List<TypeFilter> excludeFilters = new LinkedList<>();
|
||||
private final List<TypeFilter> excludeFilters = new ArrayList<>();
|
||||
|
||||
@Nullable
|
||||
private Environment environment;
|
||||
@@ -424,40 +425,38 @@ public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
|
||||
if (traceEnabled) {
|
||||
logger.trace("Scanning " + resource);
|
||||
}
|
||||
if (resource.isReadable()) {
|
||||
try {
|
||||
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
|
||||
if (isCandidateComponent(metadataReader)) {
|
||||
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
|
||||
sbd.setSource(resource);
|
||||
if (isCandidateComponent(sbd)) {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Identified candidate component class: " + resource);
|
||||
}
|
||||
candidates.add(sbd);
|
||||
}
|
||||
else {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Ignored because not a concrete top-level class: " + resource);
|
||||
}
|
||||
try {
|
||||
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
|
||||
if (isCandidateComponent(metadataReader)) {
|
||||
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
|
||||
sbd.setSource(resource);
|
||||
if (isCandidateComponent(sbd)) {
|
||||
if (debugEnabled) {
|
||||
logger.debug("Identified candidate component class: " + resource);
|
||||
}
|
||||
candidates.add(sbd);
|
||||
}
|
||||
else {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not matching any filter: " + resource);
|
||||
if (debugEnabled) {
|
||||
logger.debug("Ignored because not a concrete top-level class: " + resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new BeanDefinitionStoreException(
|
||||
"Failed to read candidate component class: " + resource, ex);
|
||||
else {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not matching any filter: " + resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
catch (FileNotFoundException ex) {
|
||||
if (traceEnabled) {
|
||||
logger.trace("Ignored because not readable: " + resource);
|
||||
logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new BeanDefinitionStoreException(
|
||||
"Failed to read candidate component class: " + resource, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException ex) {
|
||||
|
||||
+4
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -332,7 +332,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
|
||||
}
|
||||
|
||||
|
||||
private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
|
||||
private InjectionMetadata findResourceMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
|
||||
// Fall back to class name as cache key, for backwards compatibility with custom callers.
|
||||
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
|
||||
// Quick check on the concurrent map first, with minimal locking.
|
||||
@@ -352,7 +352,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
|
||||
private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
|
||||
if (!AnnotationUtils.isCandidateClass(clazz, resourceAnnotationTypes)) {
|
||||
return InjectionMetadata.EMPTY;
|
||||
}
|
||||
@@ -464,6 +464,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
|
||||
public void releaseTarget(Object target) {
|
||||
}
|
||||
};
|
||||
|
||||
ProxyFactory pf = new ProxyFactory();
|
||||
pf.setTargetSource(ts);
|
||||
if (element.lookupType.isInterface()) {
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -73,7 +73,7 @@ class ComponentScanAnnotationParser {
|
||||
}
|
||||
|
||||
|
||||
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
|
||||
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, String declaringClass) {
|
||||
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
|
||||
componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
|
||||
|
||||
|
||||
+7
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -453,8 +453,8 @@ class ConfigurationClassEnhancer {
|
||||
* instance directly. If a FactoryBean instance is fetched through the container via &-dereferencing,
|
||||
* it will not be proxied. This too is aligned with the way XML configuration works.
|
||||
*/
|
||||
private Object enhanceFactoryBean(final Object factoryBean, Class<?> exposedType,
|
||||
final ConfigurableBeanFactory beanFactory, final String beanName) {
|
||||
private Object enhanceFactoryBean(Object factoryBean, Class<?> exposedType,
|
||||
ConfigurableBeanFactory beanFactory, String beanName) {
|
||||
|
||||
try {
|
||||
Class<?> clazz = factoryBean.getClass();
|
||||
@@ -489,8 +489,8 @@ class ConfigurationClassEnhancer {
|
||||
return createCglibProxyForFactoryBean(factoryBean, beanFactory, beanName);
|
||||
}
|
||||
|
||||
private Object createInterfaceProxyForFactoryBean(final Object factoryBean, Class<?> interfaceType,
|
||||
final ConfigurableBeanFactory beanFactory, final String beanName) {
|
||||
private Object createInterfaceProxyForFactoryBean(Object factoryBean, Class<?> interfaceType,
|
||||
ConfigurableBeanFactory beanFactory, String beanName) {
|
||||
|
||||
return Proxy.newProxyInstance(
|
||||
factoryBean.getClass().getClassLoader(), new Class<?>[] {interfaceType},
|
||||
@@ -502,8 +502,8 @@ class ConfigurationClassEnhancer {
|
||||
});
|
||||
}
|
||||
|
||||
private Object createCglibProxyForFactoryBean(final Object factoryBean,
|
||||
final ConfigurableBeanFactory beanFactory, final String beanName) {
|
||||
private Object createCglibProxyForFactoryBean(Object factoryBean,
|
||||
ConfigurableBeanFactory beanFactory, String beanName) {
|
||||
|
||||
Enhancer enhancer = new Enhancer();
|
||||
enhancer.setSuperclass(factoryBean.getClass());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
* 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.
|
||||
@@ -47,6 +47,11 @@ import java.lang.annotation.Target;
|
||||
* or {@link javax.inject.Inject}: In that context, it leads to the creation of a
|
||||
* lazy-resolution proxy for all affected dependencies, as an alternative to using
|
||||
* {@link org.springframework.beans.factory.ObjectFactory} or {@link javax.inject.Provider}.
|
||||
* Please note that such a lazy-resolution proxy will always be injected; if the target
|
||||
* dependency does not exist, you will only be able to find out through an exception on
|
||||
* invocation. As a consequence, such an injection point results in unintuitive behavior
|
||||
* for optional dependencies. For a programmatic equivalent, allowing for lazy references
|
||||
* with more sophistication, consider {@link org.springframework.beans.factory.ObjectProvider}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,18 +51,20 @@ import org.springframework.util.PatternMatchUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Binder that allows for setting property values onto a target object,
|
||||
* including support for validation and binding result analysis.
|
||||
* The binding process can be customized through specifying allowed fields,
|
||||
* Binder that allows for setting property values on a target object, including
|
||||
* support for validation and binding result analysis.
|
||||
*
|
||||
* <p>The binding process can be customized by specifying allowed field patterns,
|
||||
* required fields, custom editors, etc.
|
||||
*
|
||||
* <p>Note that there are potential security implications in failing to set an array
|
||||
* of allowed fields. In the case of HTTP form POST data for example, malicious clients
|
||||
* can attempt to subvert an application by supplying values for fields or properties
|
||||
* that do not exist on the form. In some cases this could lead to illegal data being
|
||||
* set on command objects <i>or their nested objects</i>. For this reason, it is
|
||||
* <b>highly recommended to specify the {@link #setAllowedFields allowedFields} property</b>
|
||||
* on the DataBinder.
|
||||
* <p><strong>WARNING</strong>: Data binding can lead to security issues by exposing
|
||||
* parts of the object graph that are not meant to be accessed or modified by
|
||||
* external clients. Therefore the design and use of data binding should be considered
|
||||
* carefully with regard to security. For more details, please refer to the dedicated
|
||||
* sections on data binding for
|
||||
* <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-initbinder-model-design">Spring Web MVC</a> and
|
||||
* <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-initbinder-model-design">Spring WebFlux</a>
|
||||
* in the reference manual.
|
||||
*
|
||||
* <p>The binding results can be examined via the {@link BindingResult} interface,
|
||||
* extending the {@link Errors} interface: see the {@link #getBindingResult()} method.
|
||||
@@ -96,6 +98,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Rob Harrop
|
||||
* @author Stephane Nicoll
|
||||
* @author Kazuki Shimizu
|
||||
* @author Sam Brannen
|
||||
* @see #setAllowedFields
|
||||
* @see #setRequiredFields
|
||||
* @see #registerCustomEditor
|
||||
@@ -415,13 +418,21 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Register fields that should be allowed for binding. Default is all
|
||||
* fields. Restrict this for example to avoid unwanted modifications
|
||||
* by malicious users when binding HTTP request parameters.
|
||||
* <p>Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching
|
||||
* can be implemented by overriding the {@code isAllowed} method.
|
||||
* <p>Alternatively, specify a list of <i>disallowed</i> fields.
|
||||
* @param allowedFields array of field names
|
||||
* Register field patterns that should be allowed for binding.
|
||||
* <p>Default is all fields.
|
||||
* <p>Restrict this for example to avoid unwanted modifications by malicious
|
||||
* users when binding HTTP request parameters.
|
||||
* <p>Supports {@code "xxx*"}, {@code "*xxx"}, {@code "*xxx*"}, and
|
||||
* {@code "xxx*yyy"} matches (with an arbitrary number of pattern parts), as
|
||||
* well as direct equality.
|
||||
* <p>The default implementation of this method stores allowed field patterns
|
||||
* in {@linkplain PropertyAccessorUtils#canonicalPropertyName(String) canonical}
|
||||
* form. Subclasses which override this method must therefore take this into
|
||||
* account.
|
||||
* <p>More sophisticated matching can be implemented by overriding the
|
||||
* {@link #isAllowed} method.
|
||||
* <p>Alternatively, specify a list of <i>disallowed</i> field patterns.
|
||||
* @param allowedFields array of allowed field patterns
|
||||
* @see #setDisallowedFields
|
||||
* @see #isAllowed(String)
|
||||
*/
|
||||
@@ -430,8 +441,9 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the fields that should be allowed for binding.
|
||||
* @return array of field names
|
||||
* Return the field patterns that should be allowed for binding.
|
||||
* @return array of allowed field patterns
|
||||
* @see #setAllowedFields(String...)
|
||||
*/
|
||||
@Nullable
|
||||
public String[] getAllowedFields() {
|
||||
@@ -439,23 +451,44 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Register fields that should <i>not</i> be allowed for binding. Default is none.
|
||||
* Mark fields as disallowed for example to avoid unwanted modifications
|
||||
* by malicious users when binding HTTP request parameters.
|
||||
* <p>Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching
|
||||
* can be implemented by overriding the {@code isAllowed} method.
|
||||
* <p>Alternatively, specify a list of <i>allowed</i> fields.
|
||||
* @param disallowedFields array of field names
|
||||
* Register field patterns that should <i>not</i> be allowed for binding.
|
||||
* <p>Default is none.
|
||||
* <p>Mark fields as disallowed, for example to avoid unwanted
|
||||
* modifications by malicious users when binding HTTP request parameters.
|
||||
* <p>Supports {@code "xxx*"}, {@code "*xxx"}, {@code "*xxx*"}, and
|
||||
* {@code "xxx*yyy"} matches (with an arbitrary number of pattern parts), as
|
||||
* well as direct equality.
|
||||
* <p>The default implementation of this method stores disallowed field patterns
|
||||
* in {@linkplain PropertyAccessorUtils#canonicalPropertyName(String) canonical}
|
||||
* form. As of Spring Framework 5.2.21, the default implementation also transforms
|
||||
* disallowed field patterns to {@linkplain String#toLowerCase() lowercase} to
|
||||
* support case-insensitive pattern matching in {@link #isAllowed}. Subclasses
|
||||
* which override this method must therefore take both of these transformations
|
||||
* into account.
|
||||
* <p>More sophisticated matching can be implemented by overriding the
|
||||
* {@link #isAllowed} method.
|
||||
* <p>Alternatively, specify a list of <i>allowed</i> field patterns.
|
||||
* @param disallowedFields array of disallowed field patterns
|
||||
* @see #setAllowedFields
|
||||
* @see #isAllowed(String)
|
||||
*/
|
||||
public void setDisallowedFields(@Nullable String... disallowedFields) {
|
||||
this.disallowedFields = PropertyAccessorUtils.canonicalPropertyNames(disallowedFields);
|
||||
if (disallowedFields == null) {
|
||||
this.disallowedFields = null;
|
||||
}
|
||||
else {
|
||||
String[] fieldPatterns = new String[disallowedFields.length];
|
||||
for (int i = 0; i < fieldPatterns.length; i++) {
|
||||
fieldPatterns[i] = PropertyAccessorUtils.canonicalPropertyName(disallowedFields[i]).toLowerCase();
|
||||
}
|
||||
this.disallowedFields = fieldPatterns;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the fields that should <i>not</i> be allowed for binding.
|
||||
* @return array of field names
|
||||
* Return the field patterns that should <i>not</i> be allowed for binding.
|
||||
* @return array of disallowed field patterns
|
||||
* @see #setDisallowedFields(String...)
|
||||
*/
|
||||
@Nullable
|
||||
public String[] getDisallowedFields() {
|
||||
@@ -767,15 +800,20 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return if the given field is allowed for binding.
|
||||
* Invoked for each passed-in property value.
|
||||
* <p>The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
|
||||
* as well as direct equality, in the specified lists of allowed fields and
|
||||
* disallowed fields. A field matching a disallowed pattern will not be accepted
|
||||
* even if it also happens to match a pattern in the allowed list.
|
||||
* <p>Can be overridden in subclasses.
|
||||
* Determine if the given field is allowed for binding.
|
||||
* <p>Invoked for each passed-in property value.
|
||||
* <p>Checks for {@code "xxx*"}, {@code "*xxx"}, {@code "*xxx*"}, and
|
||||
* {@code "xxx*yyy"} matches (with an arbitrary number of pattern parts), as
|
||||
* well as direct equality, in the configured lists of allowed field patterns
|
||||
* and disallowed field patterns.
|
||||
* <p>Matching against allowed field patterns is case-sensitive; whereas,
|
||||
* matching against disallowed field patterns is case-insensitive.
|
||||
* <p>A field matching a disallowed pattern will not be accepted even if it
|
||||
* also happens to match a pattern in the allowed list.
|
||||
* <p>Can be overridden in subclasses, but care must be taken to honor the
|
||||
* aforementioned contract.
|
||||
* @param field the field to check
|
||||
* @return if the field is allowed
|
||||
* @return {@code true} if the field is allowed
|
||||
* @see #setAllowedFields
|
||||
* @see #setDisallowedFields
|
||||
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
|
||||
@@ -784,7 +822,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
|
||||
String[] allowed = getAllowedFields();
|
||||
String[] disallowed = getDisallowedFields();
|
||||
return ((ObjectUtils.isEmpty(allowed) || PatternMatchUtils.simpleMatch(allowed, field)) &&
|
||||
(ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field)));
|
||||
(ObjectUtils.isEmpty(disallowed) || !PatternMatchUtils.simpleMatch(disallowed, field.toLowerCase())));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+34
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -65,10 +65,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIOException;
|
||||
|
||||
/**
|
||||
* @since 13.03.2003
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 13.03.2003
|
||||
*/
|
||||
public class ProxyFactoryBeanTests {
|
||||
|
||||
@@ -631,20 +631,50 @@ public class ProxyFactoryBeanTests {
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(FROZEN_CONTEXT, CLASS));
|
||||
|
||||
Advised advised = (Advised)bf.getBean("frozen");
|
||||
Advised advised = (Advised) bf.getBean("frozen");
|
||||
assertThat(advised.isFrozen()).as("The proxy should be frozen").isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsInterfaces() throws Exception {
|
||||
public void testDetectsInterfaces() {
|
||||
ProxyFactoryBean fb = new ProxyFactoryBean();
|
||||
fb.setTarget(new TestBean());
|
||||
fb.addAdvice(new DebugInterceptor());
|
||||
fb.setBeanFactory(new DefaultListableBeanFactory());
|
||||
|
||||
ITestBean proxy = (ITestBean) fb.getObject();
|
||||
assertThat(AopUtils.isJdkDynamicProxy(proxy)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithInterceptorNames() {
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
bf.registerSingleton("debug", new DebugInterceptor());
|
||||
|
||||
ProxyFactoryBean fb = new ProxyFactoryBean();
|
||||
fb.setTarget(new TestBean());
|
||||
fb.setInterceptorNames("debug");
|
||||
fb.setBeanFactory(bf);
|
||||
|
||||
Advised proxy = (Advised) fb.getObject();
|
||||
assertThat(proxy.getAdvisors().length).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithLateInterceptorNames() {
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
bf.registerSingleton("debug", new DebugInterceptor());
|
||||
|
||||
ProxyFactoryBean fb = new ProxyFactoryBean();
|
||||
fb.setTarget(new TestBean());
|
||||
fb.setBeanFactory(bf);
|
||||
fb.getObject();
|
||||
|
||||
fb.setInterceptorNames("debug");
|
||||
Advised proxy = (Advised) fb.getObject();
|
||||
assertThat(proxy.getAdvisors().length).isEqualTo(1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fires only on void methods. Saves list of methods intercepted.
|
||||
|
||||
+2
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -25,7 +25,6 @@ import org.springframework.beans.testfixture.beans.TestBean;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/**
|
||||
* Tests cornering the issue reported in SPR-8080. If the product of a @Bean method
|
||||
* was @Autowired into a configuration class while at the same time the declaring
|
||||
@@ -34,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* 'currently in creation' status of the autowired bean and result in creating multiple
|
||||
* instances of the given @Bean, violating container scoping / singleton semantics.
|
||||
*
|
||||
* This is resolved through no longer relying on 'currently in creation' status, but
|
||||
* <p>This is resolved through no longer relying on 'currently in creation' status, but
|
||||
* rather on a thread local that informs the enhanced bean method implementation whether
|
||||
* the factory is the caller or not.
|
||||
*
|
||||
|
||||
+41
-14
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -26,7 +26,6 @@ import org.springframework.context.support.GenericXmlApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/**
|
||||
* @author Chris Beams
|
||||
* @author Juergen Hoeller
|
||||
@@ -47,6 +46,7 @@ public class DestroyMethodInferenceTests {
|
||||
WithLocalShutdownMethod c7 = ctx.getBean("c7", WithLocalShutdownMethod.class);
|
||||
WithInheritedCloseMethod c8 = ctx.getBean("c8", WithInheritedCloseMethod.class);
|
||||
WithDisposableBean c9 = ctx.getBean("c9", WithDisposableBean.class);
|
||||
WithAutoCloseable c10 = ctx.getBean("c10", WithAutoCloseable.class);
|
||||
|
||||
assertThat(c0.closed).as("c0").isFalse();
|
||||
assertThat(c1.closed).as("c1").isFalse();
|
||||
@@ -58,6 +58,8 @@ public class DestroyMethodInferenceTests {
|
||||
assertThat(c7.closed).as("c7").isFalse();
|
||||
assertThat(c8.closed).as("c8").isFalse();
|
||||
assertThat(c9.closed).as("c9").isFalse();
|
||||
assertThat(c10.closed).as("c10").isFalse();
|
||||
|
||||
ctx.close();
|
||||
assertThat(c0.closed).as("c0").isTrue();
|
||||
assertThat(c1.closed).as("c1").isTrue();
|
||||
@@ -69,6 +71,7 @@ public class DestroyMethodInferenceTests {
|
||||
assertThat(c7.closed).as("c7").isTrue();
|
||||
assertThat(c8.closed).as("c8").isFalse();
|
||||
assertThat(c9.closed).as("c9").isTrue();
|
||||
assertThat(c10.closed).as("c10").isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,21 +83,29 @@ public class DestroyMethodInferenceTests {
|
||||
WithLocalCloseMethod x3 = ctx.getBean("x3", WithLocalCloseMethod.class);
|
||||
WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class);
|
||||
WithInheritedCloseMethod x8 = ctx.getBean("x8", WithInheritedCloseMethod.class);
|
||||
WithDisposableBean x9 = ctx.getBean("x9", WithDisposableBean.class);
|
||||
WithAutoCloseable x10 = ctx.getBean("x10", WithAutoCloseable.class);
|
||||
|
||||
assertThat(x1.closed).isFalse();
|
||||
assertThat(x2.closed).isFalse();
|
||||
assertThat(x3.closed).isFalse();
|
||||
assertThat(x4.closed).isFalse();
|
||||
assertThat(x8.closed).isFalse();
|
||||
assertThat(x9.closed).isFalse();
|
||||
assertThat(x10.closed).isFalse();
|
||||
|
||||
ctx.close();
|
||||
assertThat(x1.closed).isFalse();
|
||||
assertThat(x2.closed).isTrue();
|
||||
assertThat(x3.closed).isTrue();
|
||||
assertThat(x4.closed).isFalse();
|
||||
assertThat(x8.closed).isFalse();
|
||||
assertThat(x9.closed).isTrue();
|
||||
assertThat(x10.closed).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class Config {
|
||||
|
||||
@Bean(destroyMethod = "explicitClose")
|
||||
@@ -155,6 +166,11 @@ public class DestroyMethodInferenceTests {
|
||||
public WithDisposableBean c9() {
|
||||
return new WithDisposableBean();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WithAutoCloseable c10() {
|
||||
return new WithAutoCloseable();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -189,17 +205,6 @@ public class DestroyMethodInferenceTests {
|
||||
}
|
||||
|
||||
|
||||
static class WithDisposableBean implements DisposableBean {
|
||||
|
||||
boolean closed = false;
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static class WithNoCloseMethod {
|
||||
|
||||
boolean closed = false;
|
||||
@@ -215,4 +220,26 @@ public class DestroyMethodInferenceTests {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static class WithDisposableBean implements DisposableBean {
|
||||
|
||||
boolean closed = false;
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static class WithAutoCloseable implements AutoCloseable {
|
||||
|
||||
boolean closed = false;
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+129
-137
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* Copyright 2002-2022 the original author 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,23 +64,26 @@ import org.springframework.format.support.DefaultFormattingConversionService;
|
||||
import org.springframework.format.support.FormattingConversionService;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.tests.sample.beans.BeanWithObjectProperty;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link DataBinder}.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Rob Harrop
|
||||
* @author Kazuki Shimizu
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class DataBinderTests {
|
||||
class DataBinderTests {
|
||||
|
||||
@Test
|
||||
public void testBindingNoErrors() throws BindException {
|
||||
void bindingNoErrors() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
assertThat(binder.isIgnoreUnknownFields()).isTrue();
|
||||
@@ -110,12 +113,11 @@ public class DataBinderTests {
|
||||
assertThat(ex).isEqualTo(binder.getBindingResult());
|
||||
|
||||
other.reject("xxx");
|
||||
boolean condition = !other.equals(binder.getBindingResult());
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(other).isNotEqualTo(binder.getBindingResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithDefaultConversionNoErrors() throws BindException {
|
||||
void bindingWithDefaultConversionNoErrors() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
assertThat(binder.isIgnoreUnknownFields()).isTrue();
|
||||
@@ -131,7 +133,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNestedBindingWithDefaultConversionNoErrors() throws BindException {
|
||||
void nestedBindingWithDefaultConversionNoErrors() throws BindException {
|
||||
TestBean rod = new TestBean(new TestBean());
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
assertThat(binder.isIgnoreUnknownFields()).isTrue();
|
||||
@@ -147,7 +149,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingNoErrorsNotIgnoreUnknown() {
|
||||
void bindingNoErrorsNotIgnoreUnknown() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
binder.setIgnoreUnknownFields(false);
|
||||
@@ -160,7 +162,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingNoErrorsWithInvalidField() {
|
||||
void bindingNoErrorsWithInvalidField() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -171,7 +173,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingNoErrorsWithIgnoreInvalid() {
|
||||
void bindingNoErrorsWithIgnoreInvalid() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
binder.setIgnoreInvalidFields(true);
|
||||
@@ -180,10 +182,14 @@ public class DataBinderTests {
|
||||
pvs.add("spouse.age", 32);
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
|
||||
assertThat(rod.getName()).isEqualTo("Rod");
|
||||
assertThat(rod.getSpouse()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithErrors() {
|
||||
void bindingWithErrors() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -245,7 +251,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithSystemFieldError() {
|
||||
void bindingWithSystemFieldError() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -257,7 +263,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithErrorsAndCustomEditors() {
|
||||
void bindingWithErrorsAndCustomEditors() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
binder.registerCustomEditor(String.class, "touchy", new PropertyEditorSupport() {
|
||||
@@ -325,7 +331,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithCustomEditorOnObjectField() {
|
||||
void bindingWithCustomEditorOnObjectField() {
|
||||
BeanWithObjectProperty tb = new BeanWithObjectProperty();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
binder.registerCustomEditor(Integer.class, "object", new CustomNumberEditor(Integer.class, true));
|
||||
@@ -336,7 +342,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithFormatter() {
|
||||
void bindingWithFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -368,7 +374,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithFormatter() {
|
||||
void bindingErrorWithFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -391,7 +397,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithParseExceptionFromFormatter() {
|
||||
void bindingErrorWithParseExceptionFromFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -419,7 +425,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithRuntimeExceptionFromFormatter() {
|
||||
void bindingErrorWithRuntimeExceptionFromFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -447,7 +453,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithFormatterAgainstList() {
|
||||
void bindingWithFormatterAgainstList() {
|
||||
BeanWithIntegerList tb = new BeanWithIntegerList();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -469,7 +475,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithFormatterAgainstList() {
|
||||
void bindingErrorWithFormatterAgainstList() {
|
||||
BeanWithIntegerList tb = new BeanWithIntegerList();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -492,7 +498,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithFormatterAgainstFields() {
|
||||
void bindingWithFormatterAgainstFields() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
FormattingConversionService conversionService = new FormattingConversionService();
|
||||
@@ -525,7 +531,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithFormatterAgainstFields() {
|
||||
void bindingErrorWithFormatterAgainstFields() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
binder.initDirectFieldAccess();
|
||||
@@ -549,7 +555,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithCustomFormatter() {
|
||||
void bindingWithCustomFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
binder.addCustomFormatter(new NumberStyleFormatter(), Float.class);
|
||||
@@ -578,7 +584,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithCustomFormatter() {
|
||||
void bindingErrorWithCustomFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
binder.addCustomFormatter(new NumberStyleFormatter());
|
||||
@@ -599,7 +605,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithParseExceptionFromCustomFormatter() {
|
||||
void bindingErrorWithParseExceptionFromCustomFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
|
||||
@@ -624,7 +630,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrorWithRuntimeExceptionFromCustomFormatter() {
|
||||
void bindingErrorWithRuntimeExceptionFromCustomFormatter() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
|
||||
@@ -649,7 +655,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConversionWithInappropriateStringEditor() {
|
||||
void conversionWithInappropriateStringEditor() {
|
||||
DataBinder dataBinder = new DataBinder(null);
|
||||
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
|
||||
dataBinder.setConversionService(conversionService);
|
||||
@@ -662,7 +668,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithAllowedFields() throws BindException {
|
||||
void bindingWithAllowedFields() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod);
|
||||
binder.setAllowedFields("name", "myparam");
|
||||
@@ -672,30 +678,32 @@ public class DataBinderTests {
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue();
|
||||
assertThat(rod.getAge() == 0).as("did not change age").isTrue();
|
||||
|
||||
assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod");
|
||||
assertThat(rod.getAge()).as("did not change age").isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithDisallowedFields() throws BindException {
|
||||
void bindingWithDisallowedFields() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod);
|
||||
binder.setDisallowedFields("age");
|
||||
binder.setDisallowedFields(" ", "\t", "favouriteColour", null, "age");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("name", "Rod");
|
||||
pvs.add("age", "32x");
|
||||
pvs.add("favouriteColour", "BLUE");
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
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.length).isEqualTo(1);
|
||||
assertThat(disallowedFields[0]).isEqualTo("age");
|
||||
|
||||
assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod");
|
||||
assertThat(rod.getAge()).as("did not change age").isZero();
|
||||
assertThat(rod.getFavouriteColour()).as("did not change favourite colour").isNull();
|
||||
assertThat(binder.getBindingResult().getSuppressedFields()).containsExactlyInAnyOrder("age", "favouriteColour");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithAllowedAndDisallowedFields() throws BindException {
|
||||
void bindingWithAllowedAndDisallowedFields() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod);
|
||||
binder.setAllowedFields("name", "myparam");
|
||||
@@ -706,34 +714,32 @@ public class DataBinderTests {
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
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.length).isEqualTo(1);
|
||||
assertThat(disallowedFields[0]).isEqualTo("age");
|
||||
|
||||
assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod");
|
||||
assertThat(rod.getAge()).as("did not change age").isZero();
|
||||
assertThat(binder.getBindingResult().getSuppressedFields()).containsExactly("age");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindException {
|
||||
void bindingWithOverlappingAllowedAndDisallowedFields() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod);
|
||||
binder.setAllowedFields("name", "age");
|
||||
binder.setDisallowedFields("age");
|
||||
binder.setDisallowedFields("AGE");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("name", "Rod");
|
||||
pvs.add("age", "32x");
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
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.length).isEqualTo(1);
|
||||
assertThat(disallowedFields[0]).isEqualTo("age");
|
||||
|
||||
assertThat(rod.getName()).as("changed name correctly").isEqualTo("Rod");
|
||||
assertThat(rod.getAge()).as("did not change age").isZero();
|
||||
assertThat(binder.getBindingResult().getSuppressedFields()).containsExactly("age");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException {
|
||||
void bindingWithAllowedFieldsUsingAsterisks() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
binder.setAllowedFields("nam*", "*ouchy");
|
||||
@@ -760,11 +766,11 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithAllowedAndDisallowedMapFields() throws BindException {
|
||||
void bindingWithAllowedAndDisallowedMapFields() throws BindException {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod);
|
||||
binder.setAllowedFields("someMap[key1]", "someMap[key2]");
|
||||
binder.setDisallowedFields("someMap['key3']", "someMap[key4]");
|
||||
binder.setDisallowedFields("someMap['KEY3']", "SomeMap[key4]");
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("someMap[key1]", "value1");
|
||||
@@ -774,21 +780,18 @@ public class DataBinderTests {
|
||||
|
||||
binder.bind(pvs);
|
||||
binder.close();
|
||||
assertThat(rod.getSomeMap().get("key1")).isEqualTo("value1");
|
||||
assertThat(rod.getSomeMap().get("key2")).isEqualTo("value2");
|
||||
assertThat(rod.getSomeMap().get("key3")).isNull();
|
||||
assertThat(rod.getSomeMap().get("key4")).isNull();
|
||||
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
|
||||
assertThat(disallowedFields.length).isEqualTo(2);
|
||||
assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key3]")).isTrue();
|
||||
assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key4]")).isTrue();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> someMap = (Map<String, String>) rod.getSomeMap();
|
||||
assertThat(someMap).containsOnly(entry("key1", "value1"), entry("key2", "value2"));
|
||||
assertThat(binder.getBindingResult().getSuppressedFields()).containsExactly("someMap[key3]", "someMap[key4]");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests for required field, both null, non-existing and empty strings.
|
||||
*/
|
||||
@Test
|
||||
public void testBindingWithRequiredFields() {
|
||||
void bindingWithRequiredFields() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
|
||||
@@ -819,7 +822,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithRequiredMapFields() {
|
||||
void bindingWithRequiredMapFields() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
|
||||
@@ -839,7 +842,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingWithNestedObjectCreation() {
|
||||
void bindingWithNestedObjectCreation() {
|
||||
TestBean tb = new TestBean();
|
||||
|
||||
DataBinder binder = new DataBinder(tb, "person");
|
||||
@@ -860,7 +863,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomEditorWithOldValueAccess() {
|
||||
void customEditorWithOldValueAccess() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
|
||||
@@ -885,7 +888,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomEditorForSingleProperty() {
|
||||
void customEditorForSingleProperty() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
@@ -925,7 +928,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomEditorForPrimitiveProperty() {
|
||||
void customEditorForPrimitiveProperty() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
|
||||
@@ -949,7 +952,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomEditorForAllStringProperties() {
|
||||
void customEditorForAllStringProperties() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
|
||||
@@ -981,7 +984,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomFormatterForSingleProperty() {
|
||||
void customFormatterForSingleProperty() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
@@ -1021,7 +1024,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomFormatterForPrimitiveProperty() {
|
||||
void customFormatterForPrimitiveProperty() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
|
||||
@@ -1045,7 +1048,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomFormatterForAllStringProperties() {
|
||||
void customFormatterForAllStringProperties() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
|
||||
@@ -1077,7 +1080,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJavaBeanPropertyConventions() {
|
||||
void javaBeanPropertyConventions() {
|
||||
Book book = new Book();
|
||||
DataBinder binder = new DataBinder(book);
|
||||
|
||||
@@ -1101,7 +1104,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOptionalProperty() {
|
||||
void optionalProperty() {
|
||||
OptionalHolder bean = new OptionalHolder();
|
||||
DataBinder binder = new DataBinder(bean);
|
||||
binder.setConversionService(new DefaultConversionService());
|
||||
@@ -1122,7 +1125,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidatorNoErrors() throws Exception {
|
||||
void validatorNoErrors() throws Exception {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setAge(33);
|
||||
tb.setName("Rod");
|
||||
@@ -1175,15 +1178,13 @@ public class DataBinderTests {
|
||||
assertThat(errors.getNestedPath()).isEqualTo("spouse.");
|
||||
|
||||
assertThat(errors.getErrorCount()).isEqualTo(1);
|
||||
boolean condition1 = !errors.hasGlobalErrors();
|
||||
assertThat(condition1).isTrue();
|
||||
assertThat(errors.hasGlobalErrors()).isFalse();
|
||||
assertThat(errors.getFieldErrorCount("age")).isEqualTo(1);
|
||||
boolean condition = !errors.hasFieldErrors("name");
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(errors.hasFieldErrors("name")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidatorWithErrors() {
|
||||
void validatorWithErrors() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
|
||||
@@ -1252,7 +1253,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidatorWithErrorsAndCodesPrefix() {
|
||||
void validatorWithErrorsAndCodesPrefix() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setSpouse(new TestBean());
|
||||
|
||||
@@ -1324,7 +1325,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidatorWithNestedObjectNull() {
|
||||
void validatorWithNestedObjectNull() {
|
||||
TestBean tb = new TestBean();
|
||||
Errors errors = new BeanPropertyBindingResult(tb, "tb");
|
||||
Validator testValidator = new TestBeanValidator();
|
||||
@@ -1343,7 +1344,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNestedValidatorWithoutNestedPath() {
|
||||
void nestedValidatorWithoutNestedPath() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setName("XXX");
|
||||
Errors errors = new BeanPropertyBindingResult(tb, "tb");
|
||||
@@ -1357,7 +1358,8 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingStringArrayToIntegerSet() {
|
||||
@SuppressWarnings("unchecked")
|
||||
void bindingStringArrayToIntegerSet() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class) {
|
||||
@@ -1371,12 +1373,8 @@ public class DataBinderTests {
|
||||
binder.bind(pvs);
|
||||
|
||||
assertThat(binder.getBindingResult().getFieldValue("set")).isEqualTo(tb.getSet());
|
||||
boolean condition = tb.getSet() instanceof TreeSet;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(tb.getSet().size()).isEqualTo(3);
|
||||
assertThat(tb.getSet().contains(10)).isTrue();
|
||||
assertThat(tb.getSet().contains(20)).isTrue();
|
||||
assertThat(tb.getSet().contains(30)).isTrue();
|
||||
assertThat(tb.getSet()).isInstanceOf(TreeSet.class);
|
||||
assertThat((Set<Integer>) tb.getSet()).containsExactly(10, 20, 30);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("set", null);
|
||||
@@ -1386,7 +1384,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingNullToEmptyCollection() {
|
||||
void bindingNullToEmptyCollection() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class, true));
|
||||
@@ -1394,13 +1392,12 @@ public class DataBinderTests {
|
||||
pvs.add("set", null);
|
||||
binder.bind(pvs);
|
||||
|
||||
boolean condition = tb.getSet() instanceof TreeSet;
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(tb.getSet().isEmpty()).isTrue();
|
||||
assertThat(tb.getSet()).isInstanceOf(TreeSet.class);
|
||||
assertThat(tb.getSet()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingToIndexedField() {
|
||||
void bindingToIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() {
|
||||
@@ -1439,7 +1436,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingToNestedIndexedField() {
|
||||
void bindingToNestedIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
|
||||
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
|
||||
@@ -1470,7 +1467,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEditorForNestedIndexedField() {
|
||||
void editorForNestedIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
|
||||
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
|
||||
@@ -1496,7 +1493,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpecificEditorForNestedIndexedField() {
|
||||
void specificEditorForNestedIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
|
||||
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
|
||||
@@ -1522,7 +1519,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInnerSpecificEditorForNestedIndexedField() {
|
||||
void innerSpecificEditorForNestedIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean());
|
||||
tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean());
|
||||
@@ -1548,7 +1545,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDirectBindingToIndexedField() {
|
||||
void directBindingToIndexedField() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() {
|
||||
@@ -1601,7 +1598,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDirectBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() {
|
||||
void directBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(TestBean.class, "map[key0]", new PropertyEditorSupport() {
|
||||
@@ -1632,7 +1629,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDirectBindingToEmptyIndexedFieldWithRegisteredGenericEditor() {
|
||||
void directBindingToEmptyIndexedFieldWithRegisteredGenericEditor() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() {
|
||||
@@ -1663,7 +1660,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomEditorWithSubclass() {
|
||||
void customEditorWithSubclass() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(TestBean.class, new PropertyEditorSupport() {
|
||||
@@ -1697,7 +1694,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindToStringArrayWithArrayEditor() {
|
||||
void bindToStringArrayWithArrayEditor() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(String[].class, "stringArray", new PropertyEditorSupport() {
|
||||
@@ -1709,15 +1706,12 @@ public class DataBinderTests {
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("stringArray", "a1-b2");
|
||||
binder.bind(pvs);
|
||||
boolean condition = !binder.getBindingResult().hasErrors();
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(tb.getStringArray().length).isEqualTo(2);
|
||||
assertThat(tb.getStringArray()[0]).isEqualTo("a1");
|
||||
assertThat(tb.getStringArray()[1]).isEqualTo("b2");
|
||||
assertThat(binder.getBindingResult().hasErrors()).isFalse();
|
||||
assertThat(tb.getStringArray()).containsExactly("a1", "b2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindToStringArrayWithComponentEditor() {
|
||||
void bindToStringArrayWithComponentEditor() {
|
||||
TestBean tb = new TestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
binder.registerCustomEditor(String.class, "stringArray", new PropertyEditorSupport() {
|
||||
@@ -1729,15 +1723,14 @@ public class DataBinderTests {
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("stringArray", new String[] {"a1", "b2"});
|
||||
binder.bind(pvs);
|
||||
boolean condition = !binder.getBindingResult().hasErrors();
|
||||
assertThat(condition).isTrue();
|
||||
assertThat(binder.getBindingResult().hasErrors()).isFalse();
|
||||
assertThat(tb.getStringArray().length).isEqualTo(2);
|
||||
assertThat(tb.getStringArray()[0]).isEqualTo("Xa1");
|
||||
assertThat(tb.getStringArray()[1]).isEqualTo("Xb2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindingErrors() {
|
||||
void bindingErrors() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -1764,7 +1757,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddAllErrors() {
|
||||
void addAllErrors() {
|
||||
TestBean rod = new TestBean();
|
||||
DataBinder binder = new DataBinder(rod, "person");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -1784,7 +1777,7 @@ public class DataBinderTests {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void testBindingWithResortedList() {
|
||||
void bindingWithResortedList() {
|
||||
IndexedTestBean tb = new IndexedTestBean();
|
||||
DataBinder binder = new DataBinder(tb, "tb");
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
@@ -1802,7 +1795,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRejectWithoutDefaultMessage() {
|
||||
void rejectWithoutDefaultMessage() {
|
||||
TestBean tb = new TestBean();
|
||||
tb.setName("myName");
|
||||
tb.setAge(99);
|
||||
@@ -1820,7 +1813,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindExceptionSerializable() throws Exception {
|
||||
void bindExceptionSerializable() throws Exception {
|
||||
SerializablePerson tb = new SerializablePerson();
|
||||
tb.setName("myName");
|
||||
tb.setAge(99);
|
||||
@@ -1849,27 +1842,27 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrackDisallowedFields() {
|
||||
void trackDisallowedFields() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.setAllowedFields("name", "age");
|
||||
|
||||
String name = "Rob Harrop";
|
||||
String beanName = "foobar";
|
||||
int age = 42;
|
||||
|
||||
MutablePropertyValues mpvs = new MutablePropertyValues();
|
||||
mpvs.add("name", name);
|
||||
mpvs.add("beanName", beanName);
|
||||
mpvs.add("age", age);
|
||||
mpvs.add("beanName", "foobar");
|
||||
binder.bind(mpvs);
|
||||
|
||||
assertThat(testBean.getName()).isEqualTo(name);
|
||||
String[] disallowedFields = binder.getBindingResult().getSuppressedFields();
|
||||
assertThat(disallowedFields.length).isEqualTo(1);
|
||||
assertThat(disallowedFields[0]).isEqualTo("beanName");
|
||||
assertThat(testBean.getAge()).isEqualTo(age);
|
||||
assertThat(binder.getBindingResult().getSuppressedFields()).containsExactly("beanName");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAutoGrowWithinDefaultLimit() {
|
||||
void autoGrowWithinDefaultLimit() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
|
||||
@@ -1881,7 +1874,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAutoGrowBeyondDefaultLimit() {
|
||||
void autoGrowBeyondDefaultLimit() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
|
||||
@@ -1893,7 +1886,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAutoGrowWithinCustomLimit() {
|
||||
void autoGrowWithinCustomLimit() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.setAutoGrowCollectionLimit(10);
|
||||
@@ -1906,7 +1899,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAutoGrowBeyondCustomLimit() {
|
||||
void autoGrowBeyondCustomLimit() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.setAutoGrowCollectionLimit(10);
|
||||
@@ -1919,7 +1912,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNestedGrowingList() {
|
||||
void nestedGrowingList() {
|
||||
Form form = new Form();
|
||||
DataBinder binder = new DataBinder(form, "form");
|
||||
MutablePropertyValues mpv = new MutablePropertyValues();
|
||||
@@ -1935,7 +1928,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFieldErrorAccessVariations() {
|
||||
void fieldErrorAccessVariations() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
assertThat(binder.getBindingResult().getGlobalError()).isNull();
|
||||
@@ -1956,7 +1949,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-14888
|
||||
public void testSetAutoGrowCollectionLimit() {
|
||||
void setAutoGrowCollectionLimit() {
|
||||
BeanWithIntegerList tb = new BeanWithIntegerList();
|
||||
DataBinder binder = new DataBinder(tb);
|
||||
binder.setAutoGrowCollectionLimit(257);
|
||||
@@ -1970,7 +1963,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-14888
|
||||
public void testSetAutoGrowCollectionLimitAfterInitialization() {
|
||||
void setAutoGrowCollectionLimitAfterInitialization() {
|
||||
DataBinder binder = new DataBinder(new BeanWithIntegerList());
|
||||
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
|
||||
assertThatIllegalStateException().isThrownBy(() ->
|
||||
@@ -1979,7 +1972,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-15009
|
||||
public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() {
|
||||
void setCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
|
||||
@@ -1996,7 +1989,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-15009
|
||||
public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() {
|
||||
void setCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver();
|
||||
@@ -2011,7 +2004,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-15009
|
||||
public void testSetCustomMessageCodesResolverAfterInitializeBindingResult() {
|
||||
void setCustomMessageCodesResolverAfterInitializeBindingResult() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.initBeanPropertyAccess();
|
||||
@@ -2026,7 +2019,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-15009
|
||||
public void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() {
|
||||
void setMessageCodesResolverIsNullAfterInitializeBindingResult() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.initBeanPropertyAccess();
|
||||
@@ -2040,8 +2033,7 @@ public class DataBinderTests {
|
||||
}
|
||||
|
||||
@Test // SPR-15009
|
||||
public void testCallSetMessageCodesResolverTwice() {
|
||||
|
||||
void callSetMessageCodesResolverTwice() {
|
||||
TestBean testBean = new TestBean();
|
||||
DataBinder binder = new DataBinder(testBean, "testBean");
|
||||
binder.setMessageCodesResolver(new DefaultMessageCodesResolver());
|
||||
|
||||
+7
-1
@@ -15,10 +15,16 @@
|
||||
class="org.springframework.context.annotation.DestroyMethodInferenceTests.WithInheritedCloseMethod"
|
||||
destroy-method=""/>
|
||||
|
||||
<bean id="x9"
|
||||
class="org.springframework.context.annotation.DestroyMethodInferenceTests.WithDisposableBean"
|
||||
destroy-method=""/>
|
||||
|
||||
<bean id="x10"
|
||||
class="org.springframework.context.annotation.DestroyMethodInferenceTests.WithAutoCloseable"/>
|
||||
|
||||
<beans default-destroy-method="(inferred)">
|
||||
<bean id="x3"
|
||||
class="org.springframework.context.annotation.DestroyMethodInferenceTests$WithLocalCloseMethod"/>
|
||||
|
||||
<bean id="x4"
|
||||
class="org.springframework.context.annotation.DestroyMethodInferenceTests$WithNoCloseMethod"/>
|
||||
</beans>
|
||||
|
||||
+5
-5
@@ -5,19 +5,19 @@
|
||||
|
||||
<bean id="publisher" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisher"/>
|
||||
|
||||
<bean id="publisherMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherMBean"/>
|
||||
<bean id="publisherMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherMBean"/>
|
||||
|
||||
<bean id="publisherStandardMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherStandardMBean"/>
|
||||
<bean id="publisherStandardMBean" class="org.springframework.jmx.export.NotificationPublisherTests$MyNotificationPublisherStandardMBean"/>
|
||||
|
||||
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
|
||||
<property name="beans">
|
||||
<map>
|
||||
<entry key="spring:type=Publisher" value-ref="publisher"/>
|
||||
<entry key="spring:type=PublisherMBean" value-ref="publisherMBean"/>
|
||||
<entry key="spring:type=PublisherStandardMBean" value-ref="publisherStandardMBean"/>
|
||||
<entry key="spring:type=PublisherMBean" value-ref="publisherMBean"/>
|
||||
<entry key="spring:type=PublisherStandardMBean" value-ref="publisherStandardMBean"/>
|
||||
</map>
|
||||
</property>
|
||||
<property name="server" ref="server"/>
|
||||
<property name="server" ref="server"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -53,22 +53,22 @@ dependencies {
|
||||
optional("io.reactivex:rxjava-reactive-streams")
|
||||
optional("io.reactivex.rxjava2:rxjava")
|
||||
optional("io.netty:netty-buffer")
|
||||
testCompile("io.projectreactor:reactor-test")
|
||||
testCompile("com.google.code.findbugs:jsr305")
|
||||
testCompile(project(":kotlin-coroutines"))
|
||||
testCompile("javax.annotation:javax.annotation-api")
|
||||
testCompile("javax.xml.bind:jaxb-api")
|
||||
testCompile("com.google.code.findbugs:jsr305")
|
||||
testCompile("com.fasterxml.woodstox:woodstox-core")
|
||||
testCompile("org.xmlunit:xmlunit-assertj")
|
||||
testCompile("org.xmlunit:xmlunit-matchers")
|
||||
testCompile(project(":kotlin-coroutines"))
|
||||
testCompile("io.projectreactor:reactor-test")
|
||||
testCompile("io.projectreactor.tools:blockhound")
|
||||
testFixturesImplementation("io.projectreactor:reactor-test")
|
||||
testFixturesImplementation("com.google.code.findbugs:jsr305")
|
||||
testFixturesImplementation("org.junit.platform:junit-platform-launcher")
|
||||
testFixturesImplementation("org.junit.jupiter:junit-jupiter-api")
|
||||
testFixturesImplementation("org.junit.jupiter:junit-jupiter-params")
|
||||
testFixturesImplementation("org.assertj:assertj-core")
|
||||
testFixturesImplementation("org.xmlunit:xmlunit-assertj")
|
||||
testFixturesImplementation("io.projectreactor:reactor-test")
|
||||
}
|
||||
|
||||
jar {
|
||||
|
||||
@@ -499,6 +499,7 @@ public class ReflectUtils {
|
||||
ProtectionDomain protectionDomain, Class<?> contextClass) throws Exception {
|
||||
|
||||
Class c = null;
|
||||
Throwable t = THROWABLE;
|
||||
|
||||
// Preferred option: JDK 9+ Lookup.defineClass API if ClassLoader matches
|
||||
if (contextClass != null && contextClass.getClassLoader() == loader &&
|
||||
@@ -516,6 +517,7 @@ public class ReflectUtils {
|
||||
// in case of plain LinkageError (class already defined)
|
||||
// or IllegalArgumentException (class in different package):
|
||||
// fall through to traditional ClassLoader.defineClass below
|
||||
t = target;
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
throw new CodeGenerationException(ex);
|
||||
@@ -543,6 +545,7 @@ public class ReflectUtils {
|
||||
if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) {
|
||||
throw new CodeGenerationException(ex);
|
||||
}
|
||||
t = ex;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,7 +567,7 @@ public class ReflectUtils {
|
||||
|
||||
// No defineClass variant available at all?
|
||||
if (c == null) {
|
||||
throw new CodeGenerationException(THROWABLE);
|
||||
throw new CodeGenerationException(t);
|
||||
}
|
||||
|
||||
// Force static initializers to run.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -47,7 +47,7 @@ import org.springframework.util.ReflectionUtils;
|
||||
*
|
||||
* <p>By default, depending on classpath availability, adapters are registered
|
||||
* for Reactor, RxJava 1, RxJava 2 types, {@link CompletableFuture}, Java 9+
|
||||
* {@code Flow.Publisher} and Kotlin Coroutines {@code Deferred} and {@code Flow}.
|
||||
* {@code Flow.Publisher}, and Kotlin Coroutines {@code Deferred} and {@code Flow}.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @author Sebastien Deleuze
|
||||
@@ -74,6 +74,10 @@ public class ReactiveAdapterRegistry {
|
||||
boolean reactorRegistered = false;
|
||||
if (ClassUtils.isPresent("reactor.core.publisher.Flux", classLoader)) {
|
||||
new ReactorRegistrar().registerAdapters(this);
|
||||
if (ClassUtils.isPresent("java.util.concurrent.Flow.Publisher", classLoader)) {
|
||||
// Java 9+ Flow.Publisher
|
||||
new ReactorJdkFlowAdapterRegistrar().registerAdapter(this);
|
||||
}
|
||||
reactorRegistered = true;
|
||||
}
|
||||
this.reactorPresent = reactorRegistered;
|
||||
@@ -83,20 +87,12 @@ public class ReactiveAdapterRegistry {
|
||||
ClassUtils.isPresent("rx.RxReactiveStreams", classLoader)) {
|
||||
new RxJava1Registrar().registerAdapters(this);
|
||||
}
|
||||
|
||||
// RxJava2
|
||||
if (ClassUtils.isPresent("io.reactivex.Flowable", classLoader)) {
|
||||
new RxJava2Registrar().registerAdapters(this);
|
||||
}
|
||||
|
||||
// Java 9+ Flow.Publisher
|
||||
if (ClassUtils.isPresent("java.util.concurrent.Flow.Publisher", classLoader)) {
|
||||
new ReactorJdkFlowAdapterRegistrar().registerAdapter(this);
|
||||
}
|
||||
// If not present, do nothing for the time being...
|
||||
// We can fall back on "reactive-streams-flow-bridge" (once released)
|
||||
|
||||
// Coroutines
|
||||
// Kotlin Coroutines
|
||||
if (this.reactorPresent && ClassUtils.isPresent("kotlinx.coroutines.reactor.MonoKt", classLoader)) {
|
||||
new CoroutinesRegistrar().registerAdapters(this);
|
||||
}
|
||||
@@ -226,6 +222,35 @@ public class ReactiveAdapterRegistry {
|
||||
}
|
||||
|
||||
|
||||
private static class ReactorJdkFlowAdapterRegistrar {
|
||||
|
||||
void registerAdapter(ReactiveAdapterRegistry registry) {
|
||||
// Reflectively access optional JDK 9+ API (for runtime compatibility with JDK 8)
|
||||
|
||||
try {
|
||||
String publisherName = "java.util.concurrent.Flow.Publisher";
|
||||
Class<?> publisherClass = ClassUtils.forName(publisherName, getClass().getClassLoader());
|
||||
|
||||
String adapterName = "reactor.adapter.JdkFlowAdapter";
|
||||
Class<?> flowAdapterClass = ClassUtils.forName(adapterName, getClass().getClassLoader());
|
||||
|
||||
Method toFluxMethod = flowAdapterClass.getMethod("flowPublisherToFlux", publisherClass);
|
||||
Method toFlowMethod = flowAdapterClass.getMethod("publisherToFlowPublisher", Publisher.class);
|
||||
Object emptyFlow = ReflectionUtils.invokeMethod(toFlowMethod, null, Flux.empty());
|
||||
|
||||
registry.registerReactiveType(
|
||||
ReactiveTypeDescriptor.multiValue(publisherClass, () -> emptyFlow),
|
||||
source -> (Publisher<?>) ReflectionUtils.invokeMethod(toFluxMethod, null, source),
|
||||
publisher -> ReflectionUtils.invokeMethod(toFlowMethod, null, publisher)
|
||||
);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class RxJava1Registrar {
|
||||
|
||||
void registerAdapters(ReactiveAdapterRegistry registry) {
|
||||
@@ -280,35 +305,6 @@ public class ReactiveAdapterRegistry {
|
||||
}
|
||||
|
||||
|
||||
private static class ReactorJdkFlowAdapterRegistrar {
|
||||
|
||||
void registerAdapter(ReactiveAdapterRegistry registry) {
|
||||
// TODO: remove reflection when build requires JDK 9+
|
||||
|
||||
try {
|
||||
String publisherName = "java.util.concurrent.Flow.Publisher";
|
||||
Class<?> publisherClass = ClassUtils.forName(publisherName, getClass().getClassLoader());
|
||||
|
||||
String adapterName = "reactor.adapter.JdkFlowAdapter";
|
||||
Class<?> flowAdapterClass = ClassUtils.forName(adapterName, getClass().getClassLoader());
|
||||
|
||||
Method toFluxMethod = flowAdapterClass.getMethod("flowPublisherToFlux", publisherClass);
|
||||
Method toFlowMethod = flowAdapterClass.getMethod("publisherToFlowPublisher", Publisher.class);
|
||||
Object emptyFlow = ReflectionUtils.invokeMethod(toFlowMethod, null, Flux.empty());
|
||||
|
||||
registry.registerReactiveType(
|
||||
ReactiveTypeDescriptor.multiValue(publisherClass, () -> emptyFlow),
|
||||
source -> (Publisher<?>) ReflectionUtils.invokeMethod(toFluxMethod, null, source),
|
||||
publisher -> ReflectionUtils.invokeMethod(toFlowMethod, null, publisher)
|
||||
);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ReactiveAdapter variant that wraps adapted Publishers as {@link Flux} or
|
||||
* {@link Mono} depending on {@link ReactiveTypeDescriptor#isMultiValue()}.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -47,7 +47,7 @@ import org.springframework.util.StringUtils;
|
||||
*/
|
||||
public final class Property {
|
||||
|
||||
private static Map<Property, Annotation[]> annotationCache = new ConcurrentReferenceHashMap<>();
|
||||
private static final Map<Property, Annotation[]> annotationCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
private final Class<?> objectType;
|
||||
|
||||
@@ -118,7 +118,7 @@ public final class Property {
|
||||
}
|
||||
|
||||
|
||||
// package private
|
||||
// Package private
|
||||
|
||||
MethodParameter getMethodParameter() {
|
||||
return this.methodParameter;
|
||||
@@ -132,7 +132,7 @@ public final class Property {
|
||||
}
|
||||
|
||||
|
||||
// internal helpers
|
||||
// Internal helpers
|
||||
|
||||
private String resolveName() {
|
||||
if (this.readMethod != null) {
|
||||
|
||||
+10
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -88,7 +88,15 @@ public abstract class AbstractFileResolvingResource extends AbstractResource {
|
||||
@Override
|
||||
public boolean isReadable() {
|
||||
try {
|
||||
URL url = getURL();
|
||||
return checkReadable(getURL());
|
||||
}
|
||||
catch (IOException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
boolean checkReadable(URL url) {
|
||||
try {
|
||||
if (ResourceUtils.isFileURL(url)) {
|
||||
// Proceed with file system resolution
|
||||
File file = getFile();
|
||||
|
||||
@@ -142,6 +142,18 @@ public class ClassPathResource extends AbstractFileResolvingResource {
|
||||
return (resolveURL() != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* This implementation checks for the resolution of a resource URL upfront,
|
||||
* then proceeding with {@link AbstractFileResolvingResource}'s length check.
|
||||
* @see java.lang.ClassLoader#getResource(String)
|
||||
* @see java.lang.Class#getResource(String)
|
||||
*/
|
||||
@Override
|
||||
public boolean isReadable() {
|
||||
URL url = resolveURL();
|
||||
return (url != null && checkReadable(url));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a URL for the underlying class path resource.
|
||||
* @return the resolved URL, or {@code null} if not resolvable
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
* 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.
|
||||
@@ -48,8 +48,9 @@ public interface InputStreamSource {
|
||||
* creating mail attachments. For such a use case, it is <i>required</i>
|
||||
* that each {@code getInputStream()} call returns a fresh stream.
|
||||
* @return the input stream for the underlying resource (must not be {@code null})
|
||||
* @throws java.io.FileNotFoundException if the underlying resource doesn't exist
|
||||
* @throws java.io.FileNotFoundException if the underlying resource does not exist
|
||||
* @throws IOException if the content stream could not be opened
|
||||
* @see Resource#isReadable()
|
||||
*/
|
||||
InputStream getInputStream() throws IOException;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -99,14 +99,14 @@ public interface Resource extends InputStreamSource {
|
||||
/**
|
||||
* Return a URL handle for this resource.
|
||||
* @throws IOException if the resource cannot be resolved as URL,
|
||||
* i.e. if the resource is not available as descriptor
|
||||
* i.e. if the resource is not available as a descriptor
|
||||
*/
|
||||
URL getURL() throws IOException;
|
||||
|
||||
/**
|
||||
* Return a URI handle for this resource.
|
||||
* @throws IOException if the resource cannot be resolved as URI,
|
||||
* i.e. if the resource is not available as descriptor
|
||||
* i.e. if the resource is not available as a descriptor
|
||||
* @since 2.5
|
||||
*/
|
||||
URI getURI() throws IOException;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -462,9 +462,9 @@ public class DefaultDataBuffer implements DataBuffer {
|
||||
|
||||
private void checkIndex(int index, int length) {
|
||||
assertIndex(index >= 0, "index %d must be >= 0", index);
|
||||
assertIndex(length >= 0, "length %d must be >= 0", index);
|
||||
assertIndex(length >= 0, "length %d must be >= 0", length);
|
||||
assertIndex(index <= this.capacity, "index %d must be <= %d", index, this.capacity);
|
||||
assertIndex(length <= this.capacity, "length %d must be <= %d", index, this.capacity);
|
||||
assertIndex(length <= this.capacity, "length %d must be <= %d", length, this.capacity);
|
||||
}
|
||||
|
||||
private void assertIndex(boolean expression, String format, Object... args) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -17,10 +17,12 @@
|
||||
package org.springframework.core.log;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Utility methods for formatting and logging messages.
|
||||
@@ -35,31 +37,57 @@ import org.springframework.lang.Nullable;
|
||||
*/
|
||||
public abstract class LogFormatUtils {
|
||||
|
||||
private static final Pattern NEWLINE_PATTERN = Pattern.compile("[\n\r]");
|
||||
|
||||
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("\\p{Cc}");
|
||||
|
||||
|
||||
/**
|
||||
* Format the given value via {@code toString()}, quoting it if it is a
|
||||
* {@link CharSequence}, and possibly truncating at 100 if limitLength is
|
||||
* set to true.
|
||||
* Convenience variant of {@link #formatValue(Object, int, boolean)} that
|
||||
* limits the length of a log message to 100 characters and also replaces
|
||||
* newline and control characters if {@code limitLength} is set to "true".
|
||||
* @param value the value to format
|
||||
* @param limitLength whether to truncate large formatted values (over 100)
|
||||
* @param limitLength whether to truncate the value at a length of 100
|
||||
* @return the formatted value
|
||||
*/
|
||||
public static String formatValue(@Nullable Object value, boolean limitLength) {
|
||||
return formatValue(value, (limitLength ? 100 : -1), limitLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given value via {@code toString()}, quoting it if it is a
|
||||
* {@link CharSequence}, truncating at the specified {@code maxLength}, and
|
||||
* compacting it into a single line when {@code replaceNewLines} is set.
|
||||
* @param value the value to be formatted
|
||||
* @param maxLength the max length, after which to truncate, or -1 for unlimited
|
||||
* @param replaceNewlinesAndControlCharacters whether to replace newline and
|
||||
* control characters with placeholders
|
||||
* @return the formatted value
|
||||
*/
|
||||
public static String formatValue(
|
||||
@Nullable Object value, int maxLength, boolean replaceNewlinesAndControlCharacters) {
|
||||
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String str;
|
||||
String result;
|
||||
try {
|
||||
result = ObjectUtils.nullSafeToString(value);
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
result = ObjectUtils.nullSafeToString(ex);
|
||||
}
|
||||
if (maxLength != -1) {
|
||||
result = (result.length() > maxLength ? result.substring(0, maxLength) + " (truncated)..." : result);
|
||||
}
|
||||
if (replaceNewlinesAndControlCharacters) {
|
||||
result = NEWLINE_PATTERN.matcher(result).replaceAll("<EOL>");
|
||||
result = CONTROL_CHARACTER_PATTERN.matcher(result).replaceAll("?");
|
||||
}
|
||||
if (value instanceof CharSequence) {
|
||||
str = "\"" + value + "\"";
|
||||
result = "\"" + result + "\"";
|
||||
}
|
||||
else {
|
||||
try {
|
||||
str = value.toString();
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
str = ex.toString();
|
||||
}
|
||||
}
|
||||
return (limitLength && str.length() > 100 ? str.substring(0, 100) + " (truncated)..." : str);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -77,7 +77,7 @@ public class AntPathMatcher implements PathMatcher {
|
||||
|
||||
private static final int CACHE_TURNOFF_THRESHOLD = 65536;
|
||||
|
||||
private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?}");
|
||||
private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}");
|
||||
|
||||
private static final char[] WILDCARD_CHARS = { '*', '?', '{' };
|
||||
|
||||
@@ -641,7 +641,7 @@ public class AntPathMatcher implements PathMatcher {
|
||||
*/
|
||||
protected static class AntPathStringMatcher {
|
||||
|
||||
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?}|[^/{}]|\\\\[{}])+?)}");
|
||||
private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}");
|
||||
|
||||
private static final String DEFAULT_VARIABLE_PATTERN = "(.*)";
|
||||
|
||||
|
||||
@@ -858,7 +858,7 @@ public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implemen
|
||||
Reference<K, V> ref = ConcurrentReferenceHashMap.this.getReference(entry.getKey(), Restructure.NEVER);
|
||||
Entry<K, V> otherEntry = (ref != null ? ref.get() : null);
|
||||
if (otherEntry != null) {
|
||||
return ObjectUtils.nullSafeEquals(otherEntry.getValue(), otherEntry.getValue());
|
||||
return ObjectUtils.nullSafeEquals(entry.getValue(), otherEntry.getValue());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
@@ -966,6 +966,7 @@ public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implemen
|
||||
public void remove() {
|
||||
Assert.state(this.last != null, "No element to remove");
|
||||
ConcurrentReferenceHashMap.this.remove(this.last.getKey());
|
||||
this.last = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -41,11 +41,13 @@ import org.springframework.util.comparator.NullSafeComparator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
|
||||
/**
|
||||
* Tests for {@link ConcurrentReferenceHashMap}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
class ConcurrentReferenceHashMapTests {
|
||||
|
||||
@@ -466,6 +468,7 @@ class ConcurrentReferenceHashMapTests {
|
||||
iterator.next();
|
||||
iterator.next();
|
||||
iterator.remove();
|
||||
assertThatIllegalStateException().isThrownBy(iterator::remove);
|
||||
iterator.next();
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
assertThat(this.map).hasSize(2);
|
||||
@@ -486,6 +489,26 @@ class ConcurrentReferenceHashMapTests {
|
||||
assertThat(this.map.get(2)).isEqualTo("2b");
|
||||
}
|
||||
|
||||
@Test
|
||||
void containsViaEntrySet() {
|
||||
this.map.put(1, "1");
|
||||
this.map.put(2, "2");
|
||||
this.map.put(3, "3");
|
||||
Set<Map.Entry<Integer, String>> entrySet = this.map.entrySet();
|
||||
Set<Map.Entry<Integer, String>> copy = new HashMap<>(this.map).entrySet();
|
||||
copy.forEach(entry -> assertThat(entrySet.contains(entry)).isTrue());
|
||||
this.map.put(1, "A");
|
||||
this.map.put(2, "B");
|
||||
this.map.put(3, "C");
|
||||
copy.forEach(entry -> assertThat(entrySet.contains(entry)).isFalse());
|
||||
this.map.put(1, "1");
|
||||
this.map.put(2, "2");
|
||||
this.map.put(3, "3");
|
||||
copy.forEach(entry -> assertThat(entrySet.contains(entry)).isTrue());
|
||||
entrySet.clear();
|
||||
copy.forEach(entry -> assertThat(entrySet.contains(entry)).isFalse());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled("Intended for use during development only")
|
||||
void shouldBeFasterThanSynchronizedMap() throws InterruptedException {
|
||||
@@ -583,7 +606,7 @@ class ConcurrentReferenceHashMapTests {
|
||||
}
|
||||
// For testing we want more control of the hash
|
||||
this.supplementalHash = super.getHash(o);
|
||||
return o == null ? 0 : o.hashCode();
|
||||
return (o != null ? o.hashCode() : 0);
|
||||
}
|
||||
|
||||
public int getSupplementalHash() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -20,7 +20,6 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.util.StopWatch.TaskInfo;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
@@ -41,7 +40,7 @@ class StopWatchTests {
|
||||
|
||||
private static final long duration1 = 200;
|
||||
private static final long duration2 = 100;
|
||||
private static final long fudgeFactor = 50;
|
||||
// private static final long fudgeFactor = 100;
|
||||
|
||||
private final StopWatch stopWatch = new StopWatch(ID);
|
||||
|
||||
@@ -78,18 +77,21 @@ class StopWatchTests {
|
||||
assertThat(stopWatch.currentTaskName()).isEqualTo(name1);
|
||||
stopWatch.stop();
|
||||
assertThat(stopWatch.isRunning()).isFalse();
|
||||
|
||||
/* Flaky StopWatch time assertions...
|
||||
assertThat(stopWatch.getLastTaskTimeNanos())
|
||||
.as("last task time in nanoseconds for task #1")
|
||||
.isGreaterThanOrEqualTo(millisToNanos(duration1 - fudgeFactor))
|
||||
.isLessThanOrEqualTo(millisToNanos(duration1 + fudgeFactor));
|
||||
.as("last task time in nanoseconds for task #1")
|
||||
.isGreaterThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(duration1 - fudgeFactor))
|
||||
.isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(duration1 + fudgeFactor));
|
||||
assertThat(stopWatch.getTotalTimeMillis())
|
||||
.as("total time in milliseconds for task #1")
|
||||
.isGreaterThanOrEqualTo(duration1 - fudgeFactor)
|
||||
.isLessThanOrEqualTo(duration1 + fudgeFactor);
|
||||
.as("total time in milliseconds for task #1")
|
||||
.isGreaterThanOrEqualTo(duration1 - fudgeFactor)
|
||||
.isLessThanOrEqualTo(duration1 + fudgeFactor);
|
||||
assertThat(stopWatch.getTotalTimeSeconds())
|
||||
.as("total time in seconds for task #1")
|
||||
.isGreaterThanOrEqualTo((duration1 - fudgeFactor) / 1000.0)
|
||||
.isLessThanOrEqualTo((duration1 + fudgeFactor) / 1000.0);
|
||||
.as("total time in seconds for task #1")
|
||||
.isGreaterThanOrEqualTo((duration1 - fudgeFactor) / 1000.0)
|
||||
.isLessThanOrEqualTo((duration1 + fudgeFactor) / 1000.0);
|
||||
*/
|
||||
|
||||
stopWatch.start(name2);
|
||||
Thread.sleep(duration2);
|
||||
@@ -97,18 +99,21 @@ class StopWatchTests {
|
||||
assertThat(stopWatch.currentTaskName()).isEqualTo(name2);
|
||||
stopWatch.stop();
|
||||
assertThat(stopWatch.isRunning()).isFalse();
|
||||
|
||||
/* Flaky StopWatch time assertions...
|
||||
assertThat(stopWatch.getLastTaskTimeNanos())
|
||||
.as("last task time in nanoseconds for task #2")
|
||||
.isGreaterThanOrEqualTo(millisToNanos(duration2))
|
||||
.isLessThanOrEqualTo(millisToNanos(duration2 + fudgeFactor));
|
||||
.as("last task time in nanoseconds for task #2")
|
||||
.isGreaterThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(duration2))
|
||||
.isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(duration2 + fudgeFactor));
|
||||
assertThat(stopWatch.getTotalTimeMillis())
|
||||
.as("total time in milliseconds for tasks #1 and #2")
|
||||
.isGreaterThanOrEqualTo(duration1 + duration2 - fudgeFactor)
|
||||
.isLessThanOrEqualTo(duration1 + duration2 + fudgeFactor);
|
||||
.as("total time in milliseconds for tasks #1 and #2")
|
||||
.isGreaterThanOrEqualTo(duration1 + duration2 - fudgeFactor)
|
||||
.isLessThanOrEqualTo(duration1 + duration2 + fudgeFactor);
|
||||
assertThat(stopWatch.getTotalTimeSeconds())
|
||||
.as("total time in seconds for task #2")
|
||||
.isGreaterThanOrEqualTo((duration1 + duration2 - fudgeFactor) / 1000.0)
|
||||
.isLessThanOrEqualTo((duration1 + duration2 + fudgeFactor) / 1000.0);
|
||||
.as("total time in seconds for task #2")
|
||||
.isGreaterThanOrEqualTo((duration1 + duration2 - fudgeFactor) / 1000.0)
|
||||
.isLessThanOrEqualTo((duration1 + duration2 + fudgeFactor) / 1000.0);
|
||||
*/
|
||||
|
||||
assertThat(stopWatch.getTaskCount()).isEqualTo(2);
|
||||
assertThat(stopWatch.prettyPrint()).contains(name1, name2);
|
||||
@@ -135,12 +140,8 @@ class StopWatchTests {
|
||||
assertThat(stopWatch.prettyPrint()).contains("No task info kept");
|
||||
assertThat(stopWatch.toString()).doesNotContain(name1, name2);
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class)
|
||||
.isThrownBy(stopWatch::getTaskInfo)
|
||||
.withMessage("Task info is not being kept!");
|
||||
}
|
||||
|
||||
private static long millisToNanos(long duration) {
|
||||
return MILLISECONDS.toNanos(duration);
|
||||
.isThrownBy(stopWatch::getTaskInfo)
|
||||
.withMessage("Task info is not being kept!");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -19,7 +19,7 @@ package org.springframework.expression;
|
||||
/**
|
||||
* A bean resolver can be registered with the evaluation context and will kick in
|
||||
* for bean references: {@code @myBeanName} and {@code &myBeanName} expressions.
|
||||
* The <tt>&</tt> variant syntax allows access to the factory bean where relevant.
|
||||
* The {@code &} variant syntax allows access to the factory bean where relevant.
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @since 3.0.3
|
||||
@@ -28,7 +28,7 @@ public interface BeanResolver {
|
||||
|
||||
/**
|
||||
* Look up a bean by the given name and return a corresponding instance for it.
|
||||
* For attempting access to a factory bean, the name needs a <tt>&</tt> prefix.
|
||||
* For attempting access to a factory bean, the name needs a {@code &} prefix.
|
||||
* @param context the current evaluation context
|
||||
* @param beanName the name of the bean to look up
|
||||
* @return an object representing the bean
|
||||
|
||||
+39
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -17,6 +17,7 @@
|
||||
package org.springframework.expression;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
@@ -24,12 +25,21 @@ import org.springframework.lang.Nullable;
|
||||
* Expressions are executed in an evaluation context. It is in this context that
|
||||
* references are resolved when encountered during expression evaluation.
|
||||
*
|
||||
* <p>There is a default implementation of this EvaluationContext interface:
|
||||
* {@link org.springframework.expression.spel.support.StandardEvaluationContext}
|
||||
* which can be extended, rather than having to implement everything manually.
|
||||
* <p>There are two default implementations of this interface.
|
||||
* <ul>
|
||||
* <li>{@link org.springframework.expression.spel.support.SimpleEvaluationContext
|
||||
* SimpleEvaluationContext}: a simpler builder-style {@code EvaluationContext}
|
||||
* variant for data-binding purposes, which allows for opting into several SpEL
|
||||
* features as needed.</li>
|
||||
* <li>{@link org.springframework.expression.spel.support.StandardEvaluationContext
|
||||
* StandardEvaluationContext}: a powerful and highly configurable {@code EvaluationContext}
|
||||
* implementation, which can be extended, rather than having to implement everything
|
||||
* manually.</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public interface EvaluationContext {
|
||||
@@ -85,7 +95,30 @@ public interface EvaluationContext {
|
||||
OperatorOverloader getOperatorOverloader();
|
||||
|
||||
/**
|
||||
* Set a named variable within this evaluation context to a specified value.
|
||||
* Assign the value created by the specified {@link Supplier} to a named variable
|
||||
* within this evaluation context.
|
||||
* <p>In contrast to {@link #setVariable(String, Object)}, this method should only
|
||||
* be invoked to support the assignment operator ({@code =}) within an expression.
|
||||
* <p>By default, this method delegates to {@code setVariable(String, Object)},
|
||||
* providing the value created by the {@code valueSupplier}. Concrete implementations
|
||||
* may override this <em>default</em> method to provide different semantics.
|
||||
* @param name the name of the variable to assign
|
||||
* @param valueSupplier the supplier of the value to be assigned to the variable
|
||||
* @return a {@link TypedValue} wrapping the assigned value
|
||||
* @since 5.2.24
|
||||
*/
|
||||
default TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
|
||||
TypedValue typedValue = valueSupplier.get();
|
||||
setVariable(name, typedValue.getValue());
|
||||
return typedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a named variable in this evaluation context to a specified value.
|
||||
* <p>In contrast to {@link #assignVariable(String, Supplier)}, this method
|
||||
* should only be invoked programmatically when interacting directly with the
|
||||
* {@code EvaluationContext} — for example, to provide initial
|
||||
* configuration for the context.
|
||||
* @param name the name of the variable to set
|
||||
* @param value the value to be placed in the variable
|
||||
*/
|
||||
@@ -93,7 +126,7 @@ public interface EvaluationContext {
|
||||
|
||||
/**
|
||||
* Look up a named variable within this evaluation context.
|
||||
* @param name variable to lookup
|
||||
* @param name the name of the variable to look up
|
||||
* @return the value of the variable, or {@code null} if not found
|
||||
*/
|
||||
@Nullable
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
* 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.
|
||||
@@ -40,10 +40,11 @@ public interface TypeComparator {
|
||||
* Compare two given objects.
|
||||
* @param firstObject the first object
|
||||
* @param secondObject the second object
|
||||
* @return 0 if they are equal, <0 if the first is smaller than the second,
|
||||
* or >0 if the first is larger than the second
|
||||
* @return 0 if they are equal, a negative integer if the first is smaller than
|
||||
* the second, or a positive integer if the first is larger than the second
|
||||
* @throws EvaluationException if a problem occurs during comparison
|
||||
* (or if they are not comparable in the first place)
|
||||
* @see Comparable#compareTo
|
||||
*/
|
||||
int compare(@Nullable Object firstObject, @Nullable Object secondObject) throws EvaluationException;
|
||||
|
||||
|
||||
+29
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -23,6 +23,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
@@ -38,18 +39,19 @@ import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* An ExpressionState is for maintaining per-expression-evaluation state, any changes to
|
||||
* it are not seen by other expressions but it gives a place to hold local variables and
|
||||
* ExpressionState is for maintaining per-expression-evaluation state: any changes to
|
||||
* it are not seen by other expressions, but it gives a place to hold local variables and
|
||||
* for component expressions in a compound expression to communicate state. This is in
|
||||
* contrast to the EvaluationContext, which is shared amongst expression evaluations, and
|
||||
* any changes to it will be seen by other expressions or any code that chooses to ask
|
||||
* questions of the context.
|
||||
*
|
||||
* <p>It also acts as a place for to define common utility routines that the various AST
|
||||
* <p>It also acts as a place to define common utility routines that the various AST
|
||||
* nodes might need.
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class ExpressionState {
|
||||
@@ -138,6 +140,29 @@ public class ExpressionState {
|
||||
return this.scopeRootObjects.element();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign the value created by the specified {@link Supplier} to a named variable
|
||||
* within the evaluation context.
|
||||
* <p>In contrast to {@link #setVariable(String, Object)}, this method should
|
||||
* only be invoked to support assignment within an expression.
|
||||
* @param name the name of the variable to assign
|
||||
* @param valueSupplier the supplier of the value to be assigned to the variable
|
||||
* @return a {@link TypedValue} wrapping the assigned value
|
||||
* @since 5.2.24
|
||||
* @see EvaluationContext#assignVariable(String, Supplier)
|
||||
*/
|
||||
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
|
||||
return this.relatedContext.assignVariable(name, valueSupplier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a named variable in the evaluation context to a specified value.
|
||||
* <p>In contrast to {@link #assignVariable(String, Supplier)}, this method
|
||||
* should only be invoked programmatically.
|
||||
* @param name the name of the variable to set
|
||||
* @param value the value to be placed in the variable
|
||||
* @see EvaluationContext#setVariable(String, Object)
|
||||
*/
|
||||
public void setVariable(String name, @Nullable Object value) {
|
||||
this.relatedContext.setVariable(name, value);
|
||||
}
|
||||
|
||||
+27
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2023 the original author 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 java.text.MessageFormat;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public enum SpelMessage {
|
||||
@@ -255,7 +256,31 @@ public enum SpelMessage {
|
||||
|
||||
/** @since 4.3.17 */
|
||||
FLAWED_PATTERN(Kind.ERROR, 1073,
|
||||
"Failed to efficiently evaluate pattern ''{0}'': consider redesigning it");
|
||||
"Failed to efficiently evaluate pattern ''{0}'': consider redesigning it"),
|
||||
|
||||
/** @since 5.2.20 */
|
||||
MAX_ARRAY_ELEMENTS_THRESHOLD_EXCEEDED(Kind.ERROR, 1075,
|
||||
"Array declares too many elements, exceeding the threshold of ''{0}''"),
|
||||
|
||||
/** @since 5.2.23 */
|
||||
MAX_REPEATED_TEXT_SIZE_EXCEEDED(Kind.ERROR, 1076,
|
||||
"Repeated text is too long, exceeding the threshold of ''{0}'' characters"),
|
||||
|
||||
/** @since 5.2.23 */
|
||||
MAX_REGEX_LENGTH_EXCEEDED(Kind.ERROR, 1077,
|
||||
"Regular expression is too long, exceeding the threshold of ''{0}'' characters"),
|
||||
|
||||
/** @since 5.2.24 */
|
||||
MAX_CONCATENATED_STRING_LENGTH_EXCEEDED(Kind.ERROR, 1078,
|
||||
"Concatenated string is too long, exceeding the threshold of ''{0}'' characters"),
|
||||
|
||||
/** @since 5.2.24 */
|
||||
MAX_EXPRESSION_LENGTH_EXCEEDED(Kind.ERROR, 1079,
|
||||
"SpEL expression is too long, exceeding the threshold of ''{0}'' characters"),
|
||||
|
||||
/** @since 5.2.24 */
|
||||
VARIABLE_ASSIGNMENT_NOT_SUPPORTED(Kind.ERROR, 1080,
|
||||
"Assignment to variable ''{0}'' is not supported");
|
||||
|
||||
|
||||
private final Kind kind;
|
||||
|
||||
+38
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,11 +25,19 @@ import org.springframework.lang.Nullable;
|
||||
* @author Juergen Hoeller
|
||||
* @author Phillip Webb
|
||||
* @author Andy Clement
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
* @see org.springframework.expression.spel.standard.SpelExpressionParser#SpelExpressionParser(SpelParserConfiguration)
|
||||
*/
|
||||
public class SpelParserConfiguration {
|
||||
|
||||
/**
|
||||
* Default maximum length permitted for a SpEL expression.
|
||||
* @since 5.2.24
|
||||
*/
|
||||
private static final int DEFAULT_MAX_EXPRESSION_LENGTH = 10_000;
|
||||
|
||||
|
||||
private static final SpelCompilerMode defaultCompilerMode;
|
||||
|
||||
static {
|
||||
@@ -50,6 +58,8 @@ public class SpelParserConfiguration {
|
||||
|
||||
private final int maximumAutoGrowSize;
|
||||
|
||||
private final int maximumExpressionLength;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code SpelParserConfiguration} instance with default settings.
|
||||
@@ -98,11 +108,30 @@ public class SpelParserConfiguration {
|
||||
public SpelParserConfiguration(@Nullable SpelCompilerMode compilerMode, @Nullable ClassLoader compilerClassLoader,
|
||||
boolean autoGrowNullReferences, boolean autoGrowCollections, int maximumAutoGrowSize) {
|
||||
|
||||
this(compilerMode, compilerClassLoader, autoGrowNullReferences, autoGrowCollections,
|
||||
maximumAutoGrowSize, DEFAULT_MAX_EXPRESSION_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@code SpelParserConfiguration} instance.
|
||||
* @param compilerMode the compiler mode that parsers using this configuration object should use
|
||||
* @param compilerClassLoader the ClassLoader to use as the basis for expression compilation
|
||||
* @param autoGrowNullReferences if null references should automatically grow
|
||||
* @param autoGrowCollections if collections should automatically grow
|
||||
* @param maximumAutoGrowSize the maximum size that a collection can auto grow
|
||||
* @param maximumExpressionLength the maximum length of a SpEL expression;
|
||||
* must be a positive number
|
||||
* @since 5.2.25
|
||||
*/
|
||||
public SpelParserConfiguration(@Nullable SpelCompilerMode compilerMode, @Nullable ClassLoader compilerClassLoader,
|
||||
boolean autoGrowNullReferences, boolean autoGrowCollections, int maximumAutoGrowSize, int maximumExpressionLength) {
|
||||
|
||||
this.compilerMode = (compilerMode != null ? compilerMode : defaultCompilerMode);
|
||||
this.compilerClassLoader = compilerClassLoader;
|
||||
this.autoGrowNullReferences = autoGrowNullReferences;
|
||||
this.autoGrowCollections = autoGrowCollections;
|
||||
this.maximumAutoGrowSize = maximumAutoGrowSize;
|
||||
this.maximumExpressionLength = maximumExpressionLength;
|
||||
}
|
||||
|
||||
|
||||
@@ -142,4 +171,12 @@ public class SpelParserConfiguration {
|
||||
return this.maximumAutoGrowSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the maximum number of characters that a SpEL expression can contain.
|
||||
* @since 5.2.25
|
||||
*/
|
||||
public int getMaximumExpressionLength() {
|
||||
return this.maximumExpressionLength;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -27,6 +27,7 @@ import org.springframework.expression.spel.ExpressionState;
|
||||
* <p>Example: 'someNumberProperty=42'
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class Assign extends SpelNodeImpl {
|
||||
@@ -38,9 +39,7 @@ public class Assign extends SpelNodeImpl {
|
||||
|
||||
@Override
|
||||
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
|
||||
TypedValue newValue = this.children[1].getValueInternal(state);
|
||||
getChild(0).setValue(state, newValue.getValue());
|
||||
return newValue;
|
||||
return this.children[0].setValueInternal(state, () -> this.children[1].getValueInternal(state));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -25,8 +25,8 @@ import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.expression.spel.SpelMessage;
|
||||
|
||||
/**
|
||||
* Represents a bean reference to a type, for example <tt>@foo</tt> or <tt>@'foo.bar'</tt>.
|
||||
* For a FactoryBean the syntax <tt>&foo</tt> can be used to access the factory itself.
|
||||
* Represents a bean reference to a type, for example {@code @foo} or {@code @'foo.bar'}.
|
||||
* For a FactoryBean the syntax {@code &foo} can be used to access the factory itself.
|
||||
*
|
||||
* @author Andy Clement
|
||||
*/
|
||||
@@ -64,13 +64,13 @@ public class BeanReference extends SpelNodeImpl {
|
||||
public String toStringAST() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (!this.beanName.startsWith(FACTORY_BEAN_PREFIX)) {
|
||||
sb.append("@");
|
||||
sb.append('@');
|
||||
}
|
||||
if (!this.beanName.contains(".")) {
|
||||
sb.append(this.beanName);
|
||||
}
|
||||
else {
|
||||
sb.append("'").append(this.beanName).append("'");
|
||||
sb.append('\'').append(this.beanName).append('\'');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
+9
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -17,6 +17,7 @@
|
||||
package org.springframework.expression.spel.ast;
|
||||
|
||||
import java.util.StringJoiner;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.expression.EvaluationException;
|
||||
@@ -24,13 +25,13 @@ import org.springframework.expression.TypedValue;
|
||||
import org.springframework.expression.spel.CodeFlow;
|
||||
import org.springframework.expression.spel.ExpressionState;
|
||||
import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* Represents a DOT separated expression sequence, such as
|
||||
* {@code 'property1.property2.methodOne()'}.
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class CompoundExpression extends SpelNodeImpl {
|
||||
@@ -95,8 +96,12 @@ public class CompoundExpression extends SpelNodeImpl {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(ExpressionState state, @Nullable Object value) throws EvaluationException {
|
||||
getValueRef(state).setValue(value);
|
||||
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
|
||||
throws EvaluationException {
|
||||
|
||||
TypedValue typedValue = valueSupplier.get();
|
||||
getValueRef(state).setValue(typedValue.getValue());
|
||||
return typedValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+45
-24
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author 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,11 +53,19 @@ import org.springframework.util.Assert;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class ConstructorReference extends SpelNodeImpl {
|
||||
|
||||
private boolean isArrayConstructor = false;
|
||||
/**
|
||||
* Maximum number of elements permitted in an array declaration, applying
|
||||
* to one-dimensional as well as multi-dimensional arrays.
|
||||
* @since 5.2.20
|
||||
*/
|
||||
private static final int MAX_ARRAY_ELEMENTS = 256 * 1024; // 256K
|
||||
|
||||
private final boolean isArrayConstructor;
|
||||
|
||||
@Nullable
|
||||
private SpelNodeImpl[] dimensions;
|
||||
@@ -208,14 +216,14 @@ public class ConstructorReference extends SpelNodeImpl {
|
||||
StringBuilder sb = new StringBuilder("new ");
|
||||
int index = 0;
|
||||
sb.append(getChild(index++).toStringAST());
|
||||
sb.append("(");
|
||||
sb.append('(');
|
||||
for (int i = index; i < getChildCount(); i++) {
|
||||
if (i > index) {
|
||||
sb.append(",");
|
||||
sb.append(',');
|
||||
}
|
||||
sb.append(getChild(i).toStringAST());
|
||||
}
|
||||
sb.append(")");
|
||||
sb.append(')');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@@ -234,6 +242,7 @@ public class ConstructorReference extends SpelNodeImpl {
|
||||
FormatHelper.formatClassNameForMessage(
|
||||
intendedArrayType != null ? intendedArrayType.getClass() : null));
|
||||
}
|
||||
|
||||
String type = (String) intendedArrayType;
|
||||
Class<?> componentType;
|
||||
TypeCode arrayTypeCode = TypeCode.forName(type);
|
||||
@@ -243,7 +252,8 @@ public class ConstructorReference extends SpelNodeImpl {
|
||||
else {
|
||||
componentType = arrayTypeCode.getType();
|
||||
}
|
||||
Object newArray;
|
||||
|
||||
Object newArray = null;
|
||||
if (!hasInitializer()) {
|
||||
// Confirm all dimensions were specified (for example [3][][5] is missing the 2nd dimension)
|
||||
if (this.dimensions != null) {
|
||||
@@ -252,30 +262,34 @@ public class ConstructorReference extends SpelNodeImpl {
|
||||
throw new SpelEvaluationException(getStartPosition(), SpelMessage.MISSING_ARRAY_DIMENSION);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
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);
|
||||
checkNumElements(arraySize);
|
||||
newArray = Array.newInstance(componentType, arraySize);
|
||||
}
|
||||
else {
|
||||
// Multi-dimensional - hold onto your hat!
|
||||
int[] dims = new int[this.dimensions.length];
|
||||
long numElements = 1;
|
||||
for (int d = 0; d < this.dimensions.length; d++) {
|
||||
TypedValue o = this.dimensions[d].getTypedValue(state);
|
||||
int arraySize = ExpressionUtils.toInt(typeConverter, o);
|
||||
dims[d] = arraySize;
|
||||
numElements *= arraySize;
|
||||
checkNumElements(numElements);
|
||||
}
|
||||
newArray = Array.newInstance(componentType, dims);
|
||||
}
|
||||
newArray = Array.newInstance(componentType, dims);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// There is an initializer
|
||||
if (this.dimensions == null || this.dimensions.length > 1) {
|
||||
// There is an initializer but this is a multi-dimensional array (e.g. new int[][]{{1,2},{3,4}}) - this
|
||||
// is not currently supported
|
||||
// There is an initializer but this is a multi-dimensional array (e.g. new int[][]{{1,2},{3,4}})
|
||||
// - this is not currently supported
|
||||
throw new SpelEvaluationException(getStartPosition(),
|
||||
SpelMessage.MULTIDIM_ARRAY_INITIALIZER_NOT_SUPPORTED);
|
||||
}
|
||||
@@ -326,6 +340,13 @@ public class ConstructorReference extends SpelNodeImpl {
|
||||
return new TypedValue(newArray);
|
||||
}
|
||||
|
||||
private void checkNumElements(long numElements) {
|
||||
if (numElements >= MAX_ARRAY_ELEMENTS) {
|
||||
throw new SpelEvaluationException(getStartPosition(),
|
||||
SpelMessage.MAX_ARRAY_ELEMENTS_THRESHOLD_EXCEEDED, MAX_ARRAY_ELEMENTS);
|
||||
}
|
||||
}
|
||||
|
||||
private void populateReferenceTypeArray(ExpressionState state, Object newArray, TypeConverter typeConverter,
|
||||
InlineList initializer, Class<?> componentType) {
|
||||
|
||||
|
||||
+10
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,6 +25,7 @@ import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
@@ -45,11 +46,12 @@ import org.springframework.util.ReflectionUtils;
|
||||
|
||||
/**
|
||||
* An Indexer can index into some proceeding structure to access a particular piece of it.
|
||||
* Supported structures are: strings / collections (lists/sets) / arrays.
|
||||
* <p>Supported structures are: strings / collections (lists/sets) / arrays.
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Phillip Webb
|
||||
* @author Stephane Nicoll
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
// TODO support multidimensional arrays
|
||||
@@ -102,8 +104,12 @@ public class Indexer extends SpelNodeImpl {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(ExpressionState state, @Nullable Object newValue) throws EvaluationException {
|
||||
getValueRef(state).setValue(newValue);
|
||||
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
|
||||
throws EvaluationException {
|
||||
|
||||
TypedValue typedValue = valueSupplier.get();
|
||||
getValueRef(state).setValue(typedValue.getValue());
|
||||
return typedValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+24
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -25,6 +25,8 @@ import org.springframework.expression.Operation;
|
||||
import org.springframework.expression.TypedValue;
|
||||
import org.springframework.expression.spel.CodeFlow;
|
||||
import org.springframework.expression.spel.ExpressionState;
|
||||
import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.expression.spel.SpelMessage;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.NumberUtils;
|
||||
|
||||
@@ -52,6 +54,13 @@ import org.springframework.util.NumberUtils;
|
||||
*/
|
||||
public class OpMultiply extends Operator {
|
||||
|
||||
/**
|
||||
* Maximum number of characters permitted in repeated text.
|
||||
* @since 5.2.23
|
||||
*/
|
||||
private static final int MAX_REPEATED_TEXT_SIZE = 256;
|
||||
|
||||
|
||||
public OpMultiply(int startPos, int endPos, SpelNodeImpl... operands) {
|
||||
super("*", startPos, endPos, operands);
|
||||
}
|
||||
@@ -109,10 +118,13 @@ public class OpMultiply extends Operator {
|
||||
}
|
||||
|
||||
if (leftOperand instanceof String && rightOperand instanceof Integer) {
|
||||
int repeats = (Integer) rightOperand;
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
result.append(leftOperand);
|
||||
String text = (String) leftOperand;
|
||||
int count = (Integer) rightOperand;
|
||||
int requestedSize = text.length() * count;
|
||||
checkRepeatedTextSize(requestedSize);
|
||||
StringBuilder result = new StringBuilder(requestedSize);
|
||||
for (int i = 0; i < count; i++) {
|
||||
result.append(text);
|
||||
}
|
||||
return new TypedValue(result.toString());
|
||||
}
|
||||
@@ -120,6 +132,13 @@ public class OpMultiply extends Operator {
|
||||
return state.operate(Operation.MULTIPLY, leftOperand, rightOperand);
|
||||
}
|
||||
|
||||
private void checkRepeatedTextSize(int requestedSize) {
|
||||
if (requestedSize > MAX_REPEATED_TEXT_SIZE) {
|
||||
throw new SpelEvaluationException(getStartPosition(),
|
||||
SpelMessage.MAX_REPEATED_TEXT_SIZE_EXCEEDED, MAX_REPEATED_TEXT_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCompilable() {
|
||||
if (!getLeftOperand().isCompilable()) {
|
||||
|
||||
+39
-6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -27,6 +27,8 @@ import org.springframework.expression.TypeConverter;
|
||||
import org.springframework.expression.TypedValue;
|
||||
import org.springframework.expression.spel.CodeFlow;
|
||||
import org.springframework.expression.spel.ExpressionState;
|
||||
import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.expression.spel.SpelMessage;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.NumberUtils;
|
||||
@@ -46,10 +48,18 @@ import org.springframework.util.NumberUtils;
|
||||
* @author Juergen Hoeller
|
||||
* @author Ivo Smid
|
||||
* @author Giovanni Dall'Oglio Risso
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class OpPlus extends Operator {
|
||||
|
||||
/**
|
||||
* Maximum number of characters permitted in a concatenated string.
|
||||
* @since 5.2.24
|
||||
*/
|
||||
private static final int MAX_CONCATENATED_STRING_LENGTH = 100_000;
|
||||
|
||||
|
||||
public OpPlus(int startPos, int endPos, SpelNodeImpl... operands) {
|
||||
super("+", startPos, endPos, operands);
|
||||
Assert.notEmpty(operands, "Operands must not be empty");
|
||||
@@ -123,22 +133,45 @@ public class OpPlus extends Operator {
|
||||
|
||||
if (leftOperand instanceof String && rightOperand instanceof String) {
|
||||
this.exitTypeDescriptor = "Ljava/lang/String";
|
||||
return new TypedValue((String) leftOperand + rightOperand);
|
||||
String leftString = (String) leftOperand;
|
||||
String rightString = (String) rightOperand;
|
||||
checkStringLength(leftString);
|
||||
checkStringLength(rightString);
|
||||
return concatenate(leftString, rightString);
|
||||
}
|
||||
|
||||
if (leftOperand instanceof String) {
|
||||
return new TypedValue(
|
||||
leftOperand + (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state)));
|
||||
String leftString = (String) leftOperand;
|
||||
checkStringLength(leftString);
|
||||
String rightString = (rightOperand == null ? "null" : convertTypedValueToString(operandTwoValue, state));
|
||||
checkStringLength(rightString);
|
||||
return concatenate(leftString, rightString);
|
||||
}
|
||||
|
||||
if (rightOperand instanceof String) {
|
||||
return new TypedValue(
|
||||
(leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state)) + rightOperand);
|
||||
String rightString = (String) rightOperand;
|
||||
checkStringLength(rightString);
|
||||
String leftString = (leftOperand == null ? "null" : convertTypedValueToString(operandOneValue, state));
|
||||
checkStringLength(leftString);
|
||||
return concatenate(leftString, rightString);
|
||||
}
|
||||
|
||||
return state.operate(Operation.ADD, leftOperand, rightOperand);
|
||||
}
|
||||
|
||||
private void checkStringLength(String string) {
|
||||
if (string.length() > MAX_CONCATENATED_STRING_LENGTH) {
|
||||
throw new SpelEvaluationException(getStartPosition(),
|
||||
SpelMessage.MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, MAX_CONCATENATED_STRING_LENGTH);
|
||||
}
|
||||
}
|
||||
|
||||
private TypedValue concatenate(String leftString, String rightString) {
|
||||
String result = leftString + rightString;
|
||||
checkStringLength(result);
|
||||
return new TypedValue(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toStringAST() {
|
||||
if (this.children.length < 2) { // unary plus
|
||||
|
||||
+43
-12
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author 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,19 +36,41 @@ import org.springframework.expression.spel.support.BooleanTypedValue;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class OperatorMatches extends Operator {
|
||||
|
||||
private static final int PATTERN_ACCESS_THRESHOLD = 1000000;
|
||||
|
||||
private final ConcurrentMap<String, Pattern> patternCache = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Maximum number of characters permitted in a regular expression.
|
||||
* @since 5.2.23
|
||||
*/
|
||||
private static final int MAX_REGEX_LENGTH = 1000;
|
||||
|
||||
private final ConcurrentMap<String, Pattern> patternCache;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@link OperatorMatches} instance.
|
||||
* @deprecated as of Spring Framework 5.2.23 in favor of invoking
|
||||
* {@link #OperatorMatches(ConcurrentMap, int, int, SpelNodeImpl...)}
|
||||
* with a shared pattern cache instead
|
||||
*/
|
||||
@Deprecated
|
||||
public OperatorMatches(int startPos, int endPos, SpelNodeImpl... operands) {
|
||||
super("matches", startPos, endPos, operands);
|
||||
this(new ConcurrentHashMap<>(), startPos, endPos, operands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link OperatorMatches} instance with a shared pattern cache.
|
||||
* @since 5.2.23
|
||||
*/
|
||||
public OperatorMatches(ConcurrentMap<String, Pattern> patternCache, int startPos, int endPos, SpelNodeImpl... operands) {
|
||||
super("matches", startPos, endPos, operands);
|
||||
this.patternCache = patternCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the first operand matches the regex specified as the second operand.
|
||||
@@ -62,26 +84,28 @@ public class OperatorMatches extends Operator {
|
||||
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
|
||||
SpelNodeImpl leftOp = getLeftOperand();
|
||||
SpelNodeImpl rightOp = getRightOperand();
|
||||
String left = leftOp.getValue(state, String.class);
|
||||
Object right = getRightOperand().getValue(state);
|
||||
|
||||
if (left == null) {
|
||||
String input = leftOp.getValue(state, String.class);
|
||||
if (input == null) {
|
||||
throw new SpelEvaluationException(leftOp.getStartPosition(),
|
||||
SpelMessage.INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR, (Object) null);
|
||||
}
|
||||
|
||||
Object right = rightOp.getValue(state);
|
||||
if (!(right instanceof String)) {
|
||||
throw new SpelEvaluationException(rightOp.getStartPosition(),
|
||||
SpelMessage.INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR, right);
|
||||
}
|
||||
String regex = (String) right;
|
||||
|
||||
try {
|
||||
String rightString = (String) right;
|
||||
Pattern pattern = this.patternCache.get(rightString);
|
||||
Pattern pattern = this.patternCache.get(regex);
|
||||
if (pattern == null) {
|
||||
pattern = Pattern.compile(rightString);
|
||||
this.patternCache.putIfAbsent(rightString, pattern);
|
||||
checkRegexLength(regex);
|
||||
pattern = Pattern.compile(regex);
|
||||
this.patternCache.putIfAbsent(regex, pattern);
|
||||
}
|
||||
Matcher matcher = pattern.matcher(new MatcherInput(left, new AccessCount()));
|
||||
Matcher matcher = pattern.matcher(new MatcherInput(input, new AccessCount()));
|
||||
return BooleanTypedValue.forValue(matcher.matches());
|
||||
}
|
||||
catch (PatternSyntaxException ex) {
|
||||
@@ -94,6 +118,13 @@ public class OperatorMatches extends Operator {
|
||||
}
|
||||
}
|
||||
|
||||
private void checkRegexLength(String regex) {
|
||||
if (regex.length() > MAX_REGEX_LENGTH) {
|
||||
throw new SpelEvaluationException(getStartPosition(),
|
||||
SpelMessage.MAX_REGEX_LENGTH_EXCEEDED, MAX_REGEX_LENGTH);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class AccessCount {
|
||||
|
||||
@@ -111,7 +142,7 @@ public class OperatorMatches extends Operator {
|
||||
|
||||
private final CharSequence value;
|
||||
|
||||
private AccessCount access;
|
||||
private final AccessCount access;
|
||||
|
||||
public MatcherInput(CharSequence value, AccessCount access) {
|
||||
this.value = value;
|
||||
|
||||
+9
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,6 +21,7 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.asm.Label;
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
@@ -46,6 +47,7 @@ import org.springframework.util.ReflectionUtils;
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Clark Duplichien
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class PropertyOrFieldReference extends SpelNodeImpl {
|
||||
@@ -147,8 +149,12 @@ public class PropertyOrFieldReference extends SpelNodeImpl {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(ExpressionState state, @Nullable Object newValue) throws EvaluationException {
|
||||
writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, newValue);
|
||||
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
|
||||
throws EvaluationException {
|
||||
|
||||
TypedValue typedValue = valueSupplier.get();
|
||||
writeProperty(state.getActiveContextObject(), state.getEvaluationContext(), this.name, typedValue.getValue());
|
||||
return typedValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+28
-4
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,6 +19,7 @@ package org.springframework.expression.spel.ast;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Member;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.asm.Opcodes;
|
||||
@@ -40,6 +41,7 @@ import org.springframework.util.ObjectUtils;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public abstract class SpelNodeImpl implements SpelNode, Opcodes {
|
||||
@@ -64,7 +66,7 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
|
||||
* <p>The descriptor is like the bytecode form but is slightly easier to work with.
|
||||
* It does not include the trailing semicolon (for non array reference types).
|
||||
* Some examples: Ljava/lang/String, I, [I
|
||||
*/
|
||||
*/
|
||||
@Nullable
|
||||
protected volatile String exitTypeDescriptor;
|
||||
|
||||
@@ -83,8 +85,8 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
|
||||
|
||||
|
||||
/**
|
||||
* Return {@code true} if the next child is one of the specified classes.
|
||||
*/
|
||||
* Return {@code true} if the next child is one of the specified classes.
|
||||
*/
|
||||
protected boolean nextChildIs(Class<?>... classes) {
|
||||
if (this.parent != null) {
|
||||
SpelNodeImpl[] peers = this.parent.children;
|
||||
@@ -125,6 +127,28 @@ public abstract class SpelNodeImpl implements SpelNode, Opcodes {
|
||||
|
||||
@Override
|
||||
public void setValue(ExpressionState expressionState, @Nullable Object newValue) throws EvaluationException {
|
||||
setValueInternal(expressionState, () -> new TypedValue(newValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate the expression to a node and then set the new value created by the
|
||||
* specified {@link Supplier} on that node.
|
||||
* <p>For example, if the expression evaluates to a property reference, then the
|
||||
* property will be set to the new value.
|
||||
* <p>Favor this method over {@link #setValue(ExpressionState, Object)} when
|
||||
* the value should be lazily computed.
|
||||
* <p>By default, this method throws a {@link SpelEvaluationException},
|
||||
* effectively disabling this feature. Subclasses may override this method to
|
||||
* provide an actual implementation.
|
||||
* @param expressionState the current expression state (includes the context)
|
||||
* @param valueSupplier a supplier of the new value
|
||||
* @throws EvaluationException if any problem occurs evaluating the expression or
|
||||
* setting the new value
|
||||
* @since 5.2.24
|
||||
*/
|
||||
public TypedValue setValueInternal(ExpressionState expressionState, Supplier<TypedValue> valueSupplier)
|
||||
throws EvaluationException {
|
||||
|
||||
throw new SpelEvaluationException(getStartPosition(), SpelMessage.SETVALUE_NOT_SUPPORTED, getClass());
|
||||
}
|
||||
|
||||
|
||||
+13
-8
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author 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,9 +17,11 @@
|
||||
package org.springframework.expression.spel.ast;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.asm.MethodVisitor;
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
import org.springframework.expression.EvaluationException;
|
||||
import org.springframework.expression.TypedValue;
|
||||
import org.springframework.expression.spel.CodeFlow;
|
||||
import org.springframework.expression.spel.ExpressionState;
|
||||
@@ -27,10 +29,11 @@ import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* Represents a variable reference, eg. #someVar. Note this is different to a *local*
|
||||
* variable like $someVar
|
||||
* Represents a variable reference — for example, {@code #someVar}. Note
|
||||
* that this is different than a <em>local</em> variable like {@code $someVar}.
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
public class VariableReference extends SpelNodeImpl {
|
||||
@@ -53,14 +56,14 @@ public class VariableReference extends SpelNodeImpl {
|
||||
@Override
|
||||
public ValueRef getValueRef(ExpressionState state) throws SpelEvaluationException {
|
||||
if (this.name.equals(THIS)) {
|
||||
return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(),this);
|
||||
return new ValueRef.TypedValueHolderValueRef(state.getActiveContextObject(), this);
|
||||
}
|
||||
if (this.name.equals(ROOT)) {
|
||||
return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(),this);
|
||||
return new ValueRef.TypedValueHolderValueRef(state.getRootContextObject(), this);
|
||||
}
|
||||
TypedValue result = state.lookupVariable(this.name);
|
||||
// a null value will mean either the value was null or the variable was not found
|
||||
return new VariableRef(this.name,result,state.getEvaluationContext());
|
||||
return new VariableRef(this.name, result, state.getEvaluationContext());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -90,8 +93,10 @@ public class VariableReference extends SpelNodeImpl {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(ExpressionState state, @Nullable Object value) throws SpelEvaluationException {
|
||||
state.setVariable(this.name, value);
|
||||
public TypedValue setValueInternal(ExpressionState state, Supplier<TypedValue> valueSupplier)
|
||||
throws EvaluationException {
|
||||
|
||||
return state.assignVariable(this.name, valueSupplier);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+20
-3
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,12 +21,15 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.expression.ParseException;
|
||||
import org.springframework.expression.ParserContext;
|
||||
import org.springframework.expression.common.TemplateAwareExpressionParser;
|
||||
import org.springframework.expression.spel.InternalParseException;
|
||||
import org.springframework.expression.spel.SpelEvaluationException;
|
||||
import org.springframework.expression.spel.SpelMessage;
|
||||
import org.springframework.expression.spel.SpelParseException;
|
||||
import org.springframework.expression.spel.SpelParserConfiguration;
|
||||
@@ -83,18 +86,21 @@ import org.springframework.util.StringUtils;
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Phillip Webb
|
||||
* @author Sam Brannen
|
||||
* @since 3.0
|
||||
*/
|
||||
class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
|
||||
private static final Pattern VALID_QUALIFIED_ID_PATTERN = Pattern.compile("[\\p{L}\\p{N}_$]+");
|
||||
|
||||
|
||||
private final SpelParserConfiguration configuration;
|
||||
|
||||
// For rules that build nodes, they are stacked here for return
|
||||
private final Deque<SpelNodeImpl> constructedNodes = new ArrayDeque<>();
|
||||
|
||||
// Shared cache for compiled regex patterns
|
||||
private final ConcurrentMap<String, Pattern> patternCache = new ConcurrentHashMap<>();
|
||||
|
||||
// The expression being parsed
|
||||
private String expressionString = "";
|
||||
|
||||
@@ -121,6 +127,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context)
|
||||
throws ParseException {
|
||||
|
||||
checkExpressionLength(expressionString);
|
||||
|
||||
try {
|
||||
this.expressionString = expressionString;
|
||||
Tokenizer tokenizer = new Tokenizer(expressionString);
|
||||
@@ -142,6 +150,15 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
}
|
||||
}
|
||||
|
||||
private void checkExpressionLength(String string) {
|
||||
if (string != null) {
|
||||
int maxLength = this.configuration.getMaximumExpressionLength();
|
||||
if (string.length() > maxLength) {
|
||||
throw new SpelEvaluationException(SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED, maxLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// expression
|
||||
// : logicalOrExpression
|
||||
// ( (ASSIGN^ logicalOrExpression)
|
||||
@@ -248,7 +265,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
|
||||
}
|
||||
|
||||
if (tk == TokenKind.MATCHES) {
|
||||
return new OperatorMatches(t.startPos, t.endPos, expr, rhExpr);
|
||||
return new OperatorMatches(this.patternCache, t.startPos, t.endPos, expr, rhExpr);
|
||||
}
|
||||
|
||||
Assert.isTrue(tk == TokenKind.BETWEEN, "Between token expected");
|
||||
|
||||
+14
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,6 +21,7 @@ import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
@@ -78,6 +79,7 @@ import org.springframework.lang.Nullable;
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @since 4.3.15
|
||||
* @see #forPropertyAccessors
|
||||
* @see #forReadOnlyDataBinding()
|
||||
@@ -200,6 +202,17 @@ public final class SimpleEvaluationContext implements EvaluationContext {
|
||||
return this.operatorOverloader;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code SimpleEvaluationContext} does not support variable assignment within
|
||||
* expressions.
|
||||
* @throws SpelEvaluationException with {@link SpelMessage#VARIABLE_ASSIGNMENT_NOT_SUPPORTED}
|
||||
* @since 5.2.24
|
||||
*/
|
||||
@Override
|
||||
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
|
||||
throw new SpelEvaluationException(SpelMessage.VARIABLE_ASSIGNMENT_NOT_SUPPORTED, "#" + name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVariable(String name, @Nullable Object value) {
|
||||
this.variables.put(name, value);
|
||||
|
||||
+19
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -164,6 +164,24 @@ public abstract class AbstractExpressionTests {
|
||||
*/
|
||||
protected void evaluateAndCheckError(String expression, Class<?> expectedReturnType, SpelMessage expectedMessage,
|
||||
Object... otherProperties) {
|
||||
|
||||
evaluateAndCheckError(this.parser, expression, expectedReturnType, expectedMessage, otherProperties);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate the specified expression and ensure the expected message comes out.
|
||||
* The message may have inserts and they will be checked if otherProperties is specified.
|
||||
* The first entry in otherProperties should always be the position.
|
||||
* @param parser the expression parser to use
|
||||
* @param expression the expression to evaluate
|
||||
* @param expectedReturnType ask the expression return value to be of this type if possible
|
||||
* ({@code null} indicates don't ask for conversion)
|
||||
* @param expectedMessage the expected message
|
||||
* @param otherProperties the expected inserts within the message
|
||||
*/
|
||||
protected void evaluateAndCheckError(ExpressionParser parser, String expression, Class<?> expectedReturnType, SpelMessage expectedMessage,
|
||||
Object... otherProperties) {
|
||||
|
||||
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> {
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
assertThat(expr).as("expression").isNotNull();
|
||||
|
||||
+94
-23
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -24,6 +24,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.expression.AccessException;
|
||||
@@ -38,6 +40,7 @@ import org.springframework.expression.MethodResolver;
|
||||
import org.springframework.expression.ParseException;
|
||||
import org.springframework.expression.spel.standard.SpelExpression;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
import org.springframework.expression.spel.support.SimpleEvaluationContext;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.expression.spel.support.StandardTypeLocator;
|
||||
import org.springframework.expression.spel.testresources.TestPerson;
|
||||
@@ -59,6 +62,40 @@ import static org.assertj.core.api.Assertions.within;
|
||||
*/
|
||||
public class EvaluationTests extends AbstractExpressionTests {
|
||||
|
||||
@Test
|
||||
void expressionLength() {
|
||||
String expression = String.format("'X' + '%s'", repeat(" ", 9_992));
|
||||
assertThat(expression).hasSize(10_000);
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
String result = expr.getValue(context, String.class);
|
||||
assertThat(result).hasSize(9_993);
|
||||
assertThat(result.trim()).isEqualTo("X");
|
||||
|
||||
expression = String.format("'X' + '%s'", repeat(" ", 9_993));
|
||||
assertThat(expression).hasSize(10_001);
|
||||
evaluateAndCheckError(expression, String.class, SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxExpressionLengthIsConfigurable() {
|
||||
int maximumExpressionLength = 20_000;
|
||||
|
||||
String expression = String.format("'%s'", repeat("Y", 19_998));
|
||||
assertThat(expression).hasSize(maximumExpressionLength);
|
||||
|
||||
SpelParserConfiguration configuration =
|
||||
new SpelParserConfiguration(null, null, false, false, 0, maximumExpressionLength);
|
||||
ExpressionParser parser = new SpelExpressionParser(configuration);
|
||||
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
String result = expr.getValue(String.class);
|
||||
assertThat(result).hasSize(19_998);
|
||||
|
||||
expression = String.format("'%s'", repeat("Y", 25_000));
|
||||
assertThat(expression).hasSize(25_002);
|
||||
evaluateAndCheckError(parser, expression, String.class, SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateListsOnAttemptToIndexNull01() throws EvaluationException, ParseException {
|
||||
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
|
||||
@@ -168,39 +205,47 @@ public class EvaluationTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelOperatorsMatches01() {
|
||||
evaluate("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'", "false", Boolean.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelOperatorsMatches02() {
|
||||
void matchesTrue() {
|
||||
evaluate("'5.00' matches '^-?\\d+(\\.\\d{2})?$'", "true", Boolean.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelOperatorsMatches03() {
|
||||
void matchesFalse() {
|
||||
evaluate("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'", "false", Boolean.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesWithInputConversion() {
|
||||
evaluate("27 matches '^.*2.*$'", true, Boolean.class); // conversion int --> string
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesWithNullInput() {
|
||||
evaluateAndCheckError("null matches '^.*$'", SpelMessage.INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR, 0, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelOperatorsMatches04() {
|
||||
void matchesWithNullPattern() {
|
||||
evaluateAndCheckError("'abc' matches null", SpelMessage.INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR, 14, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelOperatorsMatches05() {
|
||||
evaluate("27 matches '^.*2.*$'", true, Boolean.class); // conversion int>string
|
||||
@Test // SPR-16731
|
||||
void matchesWithPatternAccessThreshold() {
|
||||
String pattern = "^(?=[a-z0-9-]{1,47})([a-z0-9]+[-]{0,1}){1,47}[a-z0-9]{1}$";
|
||||
String expression = "'abcde-fghijklmn-o42pasdfasdfasdf.qrstuvwxyz10x.xx.yyy.zasdfasfd' matches '" + pattern + "'";
|
||||
evaluateAndCheckError(expression, SpelMessage.FLAWED_PATTERN);
|
||||
}
|
||||
|
||||
@Test // SPR-16731
|
||||
public void testMatchesWithPatternAccessThreshold() {
|
||||
String pattern = "^(?=[a-z0-9-]{1,47})([a-z0-9]+[-]{0,1}){1,47}[a-z0-9]{1}$";
|
||||
String expression = "'abcde-fghijklmn-o42pasdfasdfasdf.qrstuvwxyz10x.xx.yyy.zasdfasfd' matches \'" + pattern + "\'";
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
|
||||
expr::getValue)
|
||||
.withCauseInstanceOf(IllegalStateException.class)
|
||||
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.FLAWED_PATTERN));
|
||||
@Test
|
||||
void matchesWithPatternLengthThreshold() {
|
||||
String pattern = String.format("^(%s|X)", repeat("12345", 199));
|
||||
assertThat(pattern).hasSize(1000);
|
||||
Expression expr = parser.parseExpression("'X' matches '" + pattern + "'");
|
||||
assertThat(expr.getValue(context, Boolean.class)).isTrue();
|
||||
|
||||
pattern += "?";
|
||||
assertThat(pattern).hasSize(1001);
|
||||
evaluateAndCheckError("'abc' matches '" + pattern + "'", Boolean.class, SpelMessage.MAX_REGEX_LENGTH_EXCEEDED);
|
||||
}
|
||||
|
||||
// mixing operators
|
||||
@@ -345,9 +390,26 @@ public class EvaluationTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
// assignment
|
||||
|
||||
@Test
|
||||
public void testAssignmentToVariables01() {
|
||||
evaluate("#var1='value1'", "value1", String.class);
|
||||
void assignmentToVariableWithStandardEvaluationContext() {
|
||||
evaluate("#var1 = 'value1'", "value1", String.class);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiterString = "->", value = {
|
||||
"'#var1 = \"value1\"' -> #var1",
|
||||
"'true ? #myVar = 4 : 0' -> #myVar"
|
||||
})
|
||||
void assignmentToVariableWithSimpleEvaluationContext(String expression, String varName) {
|
||||
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
assertThatExceptionOfType(SpelEvaluationException.class)
|
||||
.isThrownBy(() -> expr.getValue(context))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.VARIABLE_ASSIGNMENT_NOT_SUPPORTED);
|
||||
assertThat(ex.getInserts()).as("inserts").containsExactly(varName);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1357,6 +1419,15 @@ public class EvaluationTests extends AbstractExpressionTests {
|
||||
}
|
||||
|
||||
|
||||
private static String repeat(String str, int count) {
|
||||
String result = "";
|
||||
for (int i = 0; i < count; i++) {
|
||||
result += str;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
static class TestClass {
|
||||
|
||||
|
||||
+46
-17
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* 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.
|
||||
@@ -46,6 +46,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
*
|
||||
* @author Andy Clement
|
||||
* @author Phillip Webb
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class MethodInvocationTests extends AbstractExpressionTests {
|
||||
|
||||
@@ -232,26 +233,54 @@ public class MethodInvocationTests extends AbstractExpressionTests {
|
||||
|
||||
@Test
|
||||
public void testVarargsInvocation01() {
|
||||
// Calling 'public int aVarargsMethod(String... strings)'
|
||||
//evaluate("aVarargsMethod('a','b','c')", 3, Integer.class);
|
||||
//evaluate("aVarargsMethod('a')", 1, Integer.class);
|
||||
evaluate("aVarargsMethod()", 0, Integer.class);
|
||||
evaluate("aVarargsMethod(1,2,3)", 3, Integer.class); // all need converting to strings
|
||||
evaluate("aVarargsMethod(1)", 1, Integer.class); // needs string conversion
|
||||
evaluate("aVarargsMethod(1,'a',3.0d)", 3, Integer.class); // first and last need conversion
|
||||
// evaluate("aVarargsMethod(new String[]{'a','b','c'})", 3, Integer.class);
|
||||
// Calling 'public String aVarargsMethod(String... strings)'
|
||||
evaluate("aVarargsMethod('a','b','c')", "[a, b, c]", String.class);
|
||||
evaluate("aVarargsMethod('a')", "[a]", String.class);
|
||||
evaluate("aVarargsMethod()", "[]", String.class);
|
||||
evaluate("aVarargsMethod(1,2,3)", "[1, 2, 3]", String.class); // all need converting to strings
|
||||
evaluate("aVarargsMethod(1)", "[1]", String.class); // needs string conversion
|
||||
evaluate("aVarargsMethod(1,'a',3.0d)", "[1, a, 3.0]", String.class); // first and last need conversion
|
||||
evaluate("aVarargsMethod(new String[]{'a','b','c'})", "[a, b, c]", String.class);
|
||||
evaluate("aVarargsMethod(new String[]{})", "[]", String.class);
|
||||
evaluate("aVarargsMethod(null)", "[null]", String.class);
|
||||
evaluate("aVarargsMethod(null,'a')", "[null, a]", String.class);
|
||||
evaluate("aVarargsMethod('a',null,'b')", "[a, null, b]", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVarargsInvocation02() {
|
||||
// Calling 'public int aVarargsMethod2(int i, String... strings)' - returns int+length_of_strings
|
||||
evaluate("aVarargsMethod2(5,'a','b','c')", 8, Integer.class);
|
||||
evaluate("aVarargsMethod2(2,'a')", 3, Integer.class);
|
||||
evaluate("aVarargsMethod2(4)", 4, Integer.class);
|
||||
evaluate("aVarargsMethod2(8,2,3)", 10, Integer.class);
|
||||
evaluate("aVarargsMethod2(9)", 9, Integer.class);
|
||||
evaluate("aVarargsMethod2(2,'a',3.0d)", 4, Integer.class);
|
||||
// evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", 11, Integer.class);
|
||||
// Calling 'public String aVarargsMethod2(int i, String... strings)'
|
||||
evaluate("aVarargsMethod2(5,'a','b','c')", "5-[a, b, c]", String.class);
|
||||
evaluate("aVarargsMethod2(2,'a')", "2-[a]", String.class);
|
||||
evaluate("aVarargsMethod2(4)", "4-[]", String.class);
|
||||
evaluate("aVarargsMethod2(8,2,3)", "8-[2, 3]", String.class);
|
||||
evaluate("aVarargsMethod2(2,'a',3.0d)", "2-[a, 3.0]", String.class);
|
||||
evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", "8-[a, b, c]", String.class);
|
||||
evaluate("aVarargsMethod2(8,new String[]{})", "8-[]", String.class);
|
||||
evaluate("aVarargsMethod2(8,null)", "8-[null]", String.class);
|
||||
evaluate("aVarargsMethod2(8,null,'a')", "8-[null, a]", String.class);
|
||||
evaluate("aVarargsMethod2(8,'a',null,'b')", "8-[a, null, b]", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVarargsOptionalInvocation() {
|
||||
// Calling 'public String optionalVarargsMethod(Optional<String>... values)'
|
||||
evaluate("optionalVarargsMethod()", "[]", String.class);
|
||||
evaluate("optionalVarargsMethod(new String[0])", "[]", String.class);
|
||||
evaluate("optionalVarargsMethod('a')", "[Optional[a]]", String.class);
|
||||
evaluate("optionalVarargsMethod('a','b','c')", "[Optional[a], Optional[b], Optional[c]]", String.class);
|
||||
evaluate("optionalVarargsMethod(9)", "[Optional[9]]", String.class);
|
||||
evaluate("optionalVarargsMethod(2,3)", "[Optional[2], Optional[3]]", String.class);
|
||||
evaluate("optionalVarargsMethod('a',3.0d)", "[Optional[a], Optional[3.0]]", String.class);
|
||||
evaluate("optionalVarargsMethod(new String[]{'a','b','c'})", "[Optional[a], Optional[b], Optional[c]]", String.class);
|
||||
// The following should actually evaluate to [Optional.empty] instead of [null],
|
||||
// but ReflectionHelper.convertArguments() passes the array type instead of
|
||||
// the array's component type as the target type to the ConversionService, and
|
||||
// GenericConversionService.convertNullSource() therefore fails to convert null
|
||||
// to Optional.empty().
|
||||
evaluate("optionalVarargsMethod(null)", "[null]", String.class);
|
||||
evaluate("optionalVarargsMethod(null,'a')", "[Optional.empty, Optional[a]]", String.class);
|
||||
evaluate("optionalVarargsMethod('a',null,'b')", "[Optional[a], Optional.empty, Optional[b]]", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+77
-16
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,10 +21,13 @@ import java.math.BigInteger;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.spel.ast.Operator;
|
||||
import org.springframework.expression.spel.standard.SpelExpression;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.expression.spel.SpelMessage.MAX_CONCATENATED_STRING_LENGTH_EXCEEDED;
|
||||
import static org.springframework.expression.spel.SpelMessage.MAX_REPEATED_TEXT_SIZE_EXCEEDED;
|
||||
|
||||
/**
|
||||
* Tests the evaluation of expressions using relational operators.
|
||||
@@ -32,6 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Giovanni Dall'Oglio Risso
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class OperatorTests extends AbstractExpressionTests {
|
||||
|
||||
@@ -324,11 +328,6 @@ public class OperatorTests extends AbstractExpressionTests {
|
||||
evaluate("3.5", 3.5d, Double.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultiplyStringInt() {
|
||||
evaluate("'a' * 5", "aaaaa", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultiplyDoubleDoubleGivesDouble() {
|
||||
evaluate("3.0d * 5.0d", 15.0d, Double.class);
|
||||
@@ -393,11 +392,7 @@ public class OperatorTests extends AbstractExpressionTests {
|
||||
evaluate("3.0f + 5.0f", 8.0f, Float.class);
|
||||
evaluate("3.0d + 5.0d", 8.0d, Double.class);
|
||||
evaluate("3 + new java.math.BigDecimal('5')", new BigDecimal("8"), BigDecimal.class);
|
||||
|
||||
evaluate("'ab' + 2", "ab2", String.class);
|
||||
evaluate("2 + 'a'", "2a", String.class);
|
||||
evaluate("'ab' + null", "abnull", String.class);
|
||||
evaluate("null + 'ab'", "nullab", String.class);
|
||||
evaluate("5 + new Integer('37')", 42, Integer.class);
|
||||
|
||||
// AST:
|
||||
SpelExpression expr = (SpelExpression)parser.parseExpression("+3");
|
||||
@@ -406,11 +401,11 @@ public class OperatorTests extends AbstractExpressionTests {
|
||||
assertThat(expr.toStringAST()).isEqualTo("(2 + 3)");
|
||||
|
||||
// use as a unary operator
|
||||
evaluate("+5d",5d,Double.class);
|
||||
evaluate("+5L",5L,Long.class);
|
||||
evaluate("+5",5,Integer.class);
|
||||
evaluate("+new java.math.BigDecimal('5')", new BigDecimal("5"),BigDecimal.class);
|
||||
evaluateAndCheckError("+'abc'",SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
|
||||
evaluate("+5d", 5d, Double.class);
|
||||
evaluate("+5L", 5L, Long.class);
|
||||
evaluate("+5", 5, Integer.class);
|
||||
evaluate("+new java.math.BigDecimal('5')", new BigDecimal("5"), BigDecimal.class);
|
||||
evaluateAndCheckError("+'abc'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
|
||||
|
||||
// string concatenation
|
||||
evaluate("'abc'+'def'","abcdef",String.class);
|
||||
@@ -576,6 +571,72 @@ public class OperatorTests extends AbstractExpressionTests {
|
||||
evaluate("'abc' != 'def'", true, Boolean.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringRepeat() {
|
||||
evaluate("'abc' * 0", "", String.class);
|
||||
evaluate("'abc' * 1", "abc", String.class);
|
||||
evaluate("'abc' * 2", "abcabc", String.class);
|
||||
|
||||
Expression expr = parser.parseExpression("'a' * 256");
|
||||
assertThat(expr.getValue(context, String.class)).hasSize(256);
|
||||
|
||||
// 4 is the position of the '*' (repeat operator)
|
||||
evaluateAndCheckError("'a' * 257", String.class, MAX_REPEATED_TEXT_SIZE_EXCEEDED, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringConcatenation() {
|
||||
evaluate("'' + ''", "", String.class);
|
||||
evaluate("'' + null", "null", String.class);
|
||||
evaluate("null + ''", "null", String.class);
|
||||
evaluate("'ab' + null", "abnull", String.class);
|
||||
evaluate("null + 'ab'", "nullab", String.class);
|
||||
evaluate("'ab' + 2", "ab2", String.class);
|
||||
evaluate("2 + 'ab'", "2ab", String.class);
|
||||
evaluate("'abc' + 'def'", "abcdef", String.class);
|
||||
|
||||
// Text is big but not too big
|
||||
final int maxSize = 100_000;
|
||||
context.setVariable("text1", createString(maxSize));
|
||||
Expression expr = parser.parseExpression("#text1 + ''");
|
||||
assertThat(expr.getValue(context, String.class)).hasSize(maxSize);
|
||||
|
||||
expr = parser.parseExpression("'' + #text1");
|
||||
assertThat(expr.getValue(context, String.class)).hasSize(maxSize);
|
||||
|
||||
context.setVariable("text1", createString(maxSize / 2));
|
||||
expr = parser.parseExpression("#text1 + #text1");
|
||||
assertThat(expr.getValue(context, String.class)).hasSize(maxSize);
|
||||
|
||||
// Text is too big
|
||||
context.setVariable("text1", createString(maxSize + 1));
|
||||
evaluateAndCheckError("#text1 + ''", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("#text1 + true", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("'' + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 3);
|
||||
evaluateAndCheckError("true + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 5);
|
||||
|
||||
context.setVariable("text1", createString(maxSize / 2));
|
||||
context.setVariable("text2", createString((maxSize / 2) + 1));
|
||||
evaluateAndCheckError("#text1 + #text2", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("#text1 + #text2 + true", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("#text1 + true + #text2", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 14);
|
||||
evaluateAndCheckError("true + #text1 + #text2", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 14);
|
||||
|
||||
evaluateAndCheckError("#text2 + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("#text2 + #text1 + true", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
evaluateAndCheckError("#text2 + true + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 14);
|
||||
evaluateAndCheckError("true + #text2 + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 14);
|
||||
|
||||
context.setVariable("text1", createString((maxSize / 3) + 1));
|
||||
evaluateAndCheckError("#text1 + #text1 + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 16);
|
||||
evaluateAndCheckError("(#text1 + #text1) + #text1", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 18);
|
||||
evaluateAndCheckError("#text1 + (#text1 + #text1)", String.class, MAX_CONCATENATED_STRING_LENGTH_EXCEEDED, 7);
|
||||
}
|
||||
|
||||
private static String createString(int size) {
|
||||
return new String(new char[size]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongs() {
|
||||
evaluate("3L == 4L", false, Boolean.class);
|
||||
|
||||
+10
-22
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2015 the original author or authors.
|
||||
* 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.
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.springframework.expression.spel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
@@ -51,10 +52,10 @@ public class TestScenarioCreator {
|
||||
TestScenarioCreator.class.getDeclaredMethod("reverseInt", Integer.TYPE, Integer.TYPE, Integer.TYPE));
|
||||
testContext.registerFunction("reverseString",
|
||||
TestScenarioCreator.class.getDeclaredMethod("reverseString", String.class));
|
||||
testContext.registerFunction("varargsFunctionReverseStringsAndMerge",
|
||||
TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge", String[].class));
|
||||
testContext.registerFunction("varargsFunctionReverseStringsAndMerge2",
|
||||
TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge2", Integer.TYPE, String[].class));
|
||||
testContext.registerFunction("varargsFunction",
|
||||
TestScenarioCreator.class.getDeclaredMethod("varargsFunction", String[].class));
|
||||
testContext.registerFunction("varargsFunction2",
|
||||
TestScenarioCreator.class.getDeclaredMethod("varargsFunction2", Integer.TYPE, String[].class));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
@@ -108,25 +109,12 @@ public class TestScenarioCreator {
|
||||
return backwards.toString();
|
||||
}
|
||||
|
||||
public static String varargsFunctionReverseStringsAndMerge(String... strings) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (strings != null) {
|
||||
for (int i = strings.length - 1; i >= 0; i--) {
|
||||
sb.append(strings[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
public static String varargsFunction(String... strings) {
|
||||
return Arrays.toString(strings);
|
||||
}
|
||||
|
||||
public static String varargsFunctionReverseStringsAndMerge2(int j, String... strings) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(j);
|
||||
if (strings != null) {
|
||||
for (int i = strings.length - 1; i >= 0; i--) {
|
||||
sb.append(strings[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
public static String varargsFunction2(int i, String... strings) {
|
||||
return String.valueOf(i) + "-" + Arrays.toString(strings);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+17
-10
@@ -58,16 +58,23 @@ public class VariableAndFunctionTests extends AbstractExpressionTests {
|
||||
|
||||
@Test
|
||||
public void testCallVarargsFunction() {
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge('a','b','c')", "cba", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge('a')", "a", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge()", "", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge('b',25)", "25b", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge(25)", "25", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge2(1,'a','b','c')", "1cba", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge2(2,'a')", "2a", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge2(3)", "3", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge2(4,'b',25)", "425b", String.class);
|
||||
evaluate("#varargsFunctionReverseStringsAndMerge2(5,25)", "525", String.class);
|
||||
evaluate("#varargsFunction()", "[]", String.class);
|
||||
evaluate("#varargsFunction(new String[0])", "[]", String.class);
|
||||
evaluate("#varargsFunction('a','b','c')", "[a, b, c]", String.class);
|
||||
evaluate("#varargsFunction('a')", "[a]", String.class);
|
||||
evaluate("#varargsFunction('b',25)", "[b, 25]", String.class);
|
||||
evaluate("#varargsFunction(25)", "[25]", String.class);
|
||||
evaluate("#varargsFunction(null)", "[null]", String.class);
|
||||
evaluate("#varargsFunction('a',null,'b')", "[a, null, b]", String.class);
|
||||
|
||||
evaluate("#varargsFunction2(9)", "9-[]", String.class);
|
||||
evaluate("#varargsFunction2(9, new String[0])", "9-[]", String.class);
|
||||
evaluate("#varargsFunction2(9,'a','b','c')", "9-[a, b, c]", String.class);
|
||||
evaluate("#varargsFunction2(9,'a')", "9-[a]", String.class);
|
||||
evaluate("#varargsFunction2(9,'b',25)", "9-[b, 25]", String.class);
|
||||
evaluate("#varargsFunction2(9,25)", "9-[25]", String.class);
|
||||
evaluate("#varargsFunction2(9,null)", "9-[null]", String.class);
|
||||
evaluate("#varargsFunction2(9,'a',null,'b')", "9-[a, null, b]", String.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+13
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -21,7 +21,9 @@ import java.util.function.Consumer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.ExpressionException;
|
||||
import org.springframework.expression.ExpressionParser;
|
||||
import org.springframework.expression.spel.SpelMessage;
|
||||
import org.springframework.expression.spel.SpelNode;
|
||||
import org.springframework.expression.spel.SpelParseException;
|
||||
@@ -35,9 +37,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
/**
|
||||
* @author Andy Clement
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class SpelParserTests {
|
||||
|
||||
@Test // gh-30464
|
||||
public void nullExpression() {
|
||||
ExpressionParser parser = new SpelExpressionParser();
|
||||
String expression = null;
|
||||
Expression expr = parser.parseExpression(expression);
|
||||
Object result = expr.getValue();
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void theMostBasic() {
|
||||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
|
||||
+12
-9
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
* 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.
|
||||
@@ -17,11 +17,13 @@
|
||||
package org.springframework.expression.spel.testresources;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
@@ -190,16 +192,17 @@ public class Inventor {
|
||||
return a + b + c;
|
||||
}
|
||||
|
||||
public int aVarargsMethod(String... strings) {
|
||||
if (strings == null)
|
||||
return 0;
|
||||
return strings.length;
|
||||
public String aVarargsMethod(String... strings) {
|
||||
return Arrays.toString(strings);
|
||||
}
|
||||
|
||||
public int aVarargsMethod2(int i, String... strings) {
|
||||
if (strings == null)
|
||||
return i;
|
||||
return strings.length + i;
|
||||
public String aVarargsMethod2(int i, String... strings) {
|
||||
return String.valueOf(i) + "-" + Arrays.toString(strings);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public String optionalVarargsMethod(Optional<String>... values) {
|
||||
return Arrays.toString(values);
|
||||
}
|
||||
|
||||
public Inventor(String... strings) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -21,22 +21,21 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.IncorrectResultSizeDataAccessException;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.jdbc.support.rowset.SqlRowSet;
|
||||
import org.springframework.lang.Nullable;
|
||||
|
||||
/**
|
||||
* Interface specifying a basic set of JDBC operations.
|
||||
* Implemented by {@link JdbcTemplate}. Not often used directly, but a useful
|
||||
*
|
||||
* <p>Implemented by {@link JdbcTemplate}. Not often used directly, but a useful
|
||||
* option to enhance testability, as it can easily be mocked or stubbed.
|
||||
*
|
||||
* <p>Alternatively, the standard JDBC infrastructure can be mocked.
|
||||
* However, mocking this interface constitutes significantly less work.
|
||||
* As an alternative to a mock objects approach to testing data access code,
|
||||
* consider the powerful integration testing support provided in the
|
||||
* {@code org.springframework.test} package, shipped in
|
||||
* {@code spring-test.jar}.
|
||||
* consider the powerful integration testing support provided via the <em>Spring
|
||||
* TestContext Framework</em>, in the {@code spring-test} artifact.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
@@ -143,8 +142,8 @@ public interface JdbcOperations {
|
||||
* @param rowMapper a callback that will map one object per row
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if there is any problem executing the query
|
||||
* @see #queryForObject(String, RowMapper, Object...)
|
||||
*/
|
||||
@@ -163,8 +162,10 @@ public interface JdbcOperations {
|
||||
* @param sql the SQL query to execute
|
||||
* @param requiredType the type that the result object is expected to match
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not return
|
||||
* exactly one row, or does not return exactly one column in that row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if there is any problem executing the query
|
||||
* @see #queryForObject(String, Class, Object...)
|
||||
*/
|
||||
@@ -181,8 +182,8 @@ public interface JdbcOperations {
|
||||
* mapped to a Map (one entry for each column, using the column name as the key).
|
||||
* @param sql the SQL query to execute
|
||||
* @return the result Map (one entry per column, with column name as key)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if there is any problem executing the query
|
||||
* @see #queryForMap(String, Object...)
|
||||
* @see ColumnMapRowMapper
|
||||
@@ -528,8 +529,8 @@ public interface JdbcOperations {
|
||||
* @param rowMapper a callback that will map one object per row
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
*/
|
||||
@Nullable
|
||||
@@ -548,8 +549,8 @@ public interface JdbcOperations {
|
||||
* @param rowMapper a callback that will map one object per row
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
*/
|
||||
@Nullable
|
||||
@@ -567,8 +568,8 @@ public interface JdbcOperations {
|
||||
* only the argument value but also the SQL type and optionally the scale
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
* @since 3.0.1
|
||||
*/
|
||||
@@ -586,8 +587,10 @@ public interface JdbcOperations {
|
||||
* (constants from {@code java.sql.Types})
|
||||
* @param requiredType the type that the result object is expected to match
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not return
|
||||
* exactly one row, or does not return exactly one column in that row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see #queryForObject(String, Class)
|
||||
* @see java.sql.Types
|
||||
@@ -608,8 +611,10 @@ public interface JdbcOperations {
|
||||
* only the argument value but also the SQL type and optionally the scale
|
||||
* @param requiredType the type that the result object is expected to match
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not return
|
||||
* exactly one row, or does not return exactly one column in that row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see #queryForObject(String, Class)
|
||||
*/
|
||||
@@ -628,8 +633,10 @@ public interface JdbcOperations {
|
||||
* may also contain {@link SqlParameterValue} objects which indicate not
|
||||
* only the argument value but also the SQL type and optionally the scale
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not return
|
||||
* exactly one row, or does not return exactly one column in that row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if the query fails
|
||||
* @since 3.0.1
|
||||
* @see #queryForObject(String, Class)
|
||||
@@ -647,8 +654,8 @@ public interface JdbcOperations {
|
||||
* @param argTypes the SQL types of the arguments
|
||||
* (constants from {@code java.sql.Types})
|
||||
* @return the result Map (one entry per column, with column name as key)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see #queryForMap(String)
|
||||
* @see ColumnMapRowMapper
|
||||
@@ -671,8 +678,8 @@ public interface JdbcOperations {
|
||||
* only the argument value but also the SQL type and optionally the scale
|
||||
* @return the result Map (one entry for each column, using the
|
||||
* column name as the key)
|
||||
* @throws IncorrectResultSizeDataAccessException if the query does not
|
||||
* return exactly one row
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see #queryForMap(String)
|
||||
* @see ColumnMapRowMapper
|
||||
|
||||
+10
-9
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -236,8 +236,7 @@ public interface NamedParameterJdbcOperations {
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row, or does not return exactly
|
||||
* one column in that row
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
*/
|
||||
@Nullable
|
||||
@@ -255,8 +254,7 @@ public interface NamedParameterJdbcOperations {
|
||||
* @return the single mapped object (may be {@code null} if the given
|
||||
* {@link RowMapper} returned {@code} null)
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row, or does not return exactly
|
||||
* one column in that row
|
||||
* if the query does not return exactly one row
|
||||
* @throws DataAccessException if the query fails
|
||||
*/
|
||||
@Nullable
|
||||
@@ -273,10 +271,12 @@ public interface NamedParameterJdbcOperations {
|
||||
* @param requiredType the type that the result object is expected to match
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row, or does not return exactly
|
||||
* one column in that row
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class)
|
||||
* @see org.springframework.jdbc.core.SingleColumnRowMapper
|
||||
*/
|
||||
@Nullable
|
||||
<T> T queryForObject(String sql, SqlParameterSource paramSource, Class<T> requiredType)
|
||||
@@ -293,8 +293,9 @@ public interface NamedParameterJdbcOperations {
|
||||
* @param requiredType the type that the result object is expected to match
|
||||
* @return the result object of the required type, or {@code null} in case of SQL NULL
|
||||
* @throws org.springframework.dao.IncorrectResultSizeDataAccessException
|
||||
* if the query does not return exactly one row, or does not return exactly
|
||||
* one column in that row
|
||||
* if the query does not return exactly one row
|
||||
* @throws org.springframework.jdbc.IncorrectResultSetColumnCountException
|
||||
* if the query does not return a row containing a single column
|
||||
* @throws DataAccessException if the query fails
|
||||
* @see org.springframework.jdbc.core.JdbcTemplate#queryForObject(String, Class)
|
||||
*/
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2017 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -53,7 +53,7 @@ import org.springframework.lang.Nullable;
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5
|
||||
* @see java.sql.SQLTransientException
|
||||
* @see java.sql.SQLTransientException
|
||||
* @see java.sql.SQLNonTransientException
|
||||
* @see java.sql.SQLRecoverableException
|
||||
*/
|
||||
public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLExceptionTranslator {
|
||||
|
||||
+7
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
* 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.
|
||||
@@ -16,8 +16,8 @@
|
||||
|
||||
package org.springframework.jms.listener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.jms.Connection;
|
||||
@@ -81,9 +81,9 @@ public abstract class AbstractJmsListeningContainer extends JmsDestinationAccess
|
||||
|
||||
private boolean active = false;
|
||||
|
||||
private volatile boolean running = false;
|
||||
private volatile boolean running;
|
||||
|
||||
private final List<Object> pausedTasks = new LinkedList<>();
|
||||
private final List<Object> pausedTasks = new ArrayList<>();
|
||||
|
||||
protected final Object lifecycleMonitor = new Object();
|
||||
|
||||
@@ -582,13 +582,13 @@ public abstract class AbstractJmsListeningContainer extends JmsDestinationAccess
|
||||
/**
|
||||
* Log a task that has been rejected by {@link #doRescheduleTask}.
|
||||
* <p>The default implementation simply logs a corresponding message
|
||||
* at debug level.
|
||||
* at warn level.
|
||||
* @param task the rejected task object
|
||||
* @param ex the exception thrown from {@link #doRescheduleTask}
|
||||
*/
|
||||
protected void logRejectedTask(Object task, RuntimeException ex) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Listener container task [" + task + "] has been rejected and paused: " + ex);
|
||||
if (logger.isWarnEnabled()) {
|
||||
logger.warn("Listener container task [" + task + "] has been rejected and paused: " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -416,21 +416,21 @@ public class HandlerMethod {
|
||||
private class ReturnValueMethodParameter extends HandlerMethodParameter {
|
||||
|
||||
@Nullable
|
||||
private final Object returnValue;
|
||||
private final Class<?> returnValueType;
|
||||
|
||||
public ReturnValueMethodParameter(@Nullable Object returnValue) {
|
||||
super(-1);
|
||||
this.returnValue = returnValue;
|
||||
this.returnValueType = (returnValue != null ? returnValue.getClass() : null);
|
||||
}
|
||||
|
||||
protected ReturnValueMethodParameter(ReturnValueMethodParameter original) {
|
||||
super(original);
|
||||
this.returnValue = original.returnValue;
|
||||
this.returnValueType = original.returnValueType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getParameterType() {
|
||||
return (this.returnValue != null ? this.returnValue.getClass() : super.getParameterType());
|
||||
return (this.returnValueType != null ? this.returnValueType : super.getParameterType());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+7
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -306,6 +306,12 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
|
||||
else if (SimpMessageType.CONNECT.equals(messageType)) {
|
||||
logMessage(message);
|
||||
if (sessionId != null) {
|
||||
if (this.sessions.get(sessionId) != null) {
|
||||
if (logger.isWarnEnabled()) {
|
||||
logger.warn("Ignoring CONNECT in session " + sessionId + ". Already connected.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
long[] heartbeatIn = SimpMessageHeaderAccessor.getHeartbeat(headers);
|
||||
long[] heartbeatOut = getHeartbeatValue();
|
||||
Principal user = SimpMessageHeaderAccessor.getUser(headers);
|
||||
|
||||
+7
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -532,6 +532,12 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
|
||||
}
|
||||
|
||||
if (StompCommand.CONNECT.equals(command) || StompCommand.STOMP.equals(command)) {
|
||||
if (this.connectionHandlers.get(sessionId) != null) {
|
||||
if (logger.isWarnEnabled()) {
|
||||
logger.warn("Ignoring CONNECT in session " + sessionId + ". Already connected.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug(stompAccessor.getShortLogMessage(EMPTY_PAYLOAD));
|
||||
}
|
||||
|
||||
+25
-1
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2022 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -223,6 +223,30 @@ class StompBrokerRelayMessageHandlerTests {
|
||||
assertThat(captor.getValue()).isSameAs(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyConnected() {
|
||||
|
||||
this.brokerRelay.start();
|
||||
|
||||
Message<byte[]> connect = connectMessage("sess1", "joe");
|
||||
this.brokerRelay.handleMessage(connect);
|
||||
|
||||
assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2);
|
||||
|
||||
StompHeaderAccessor headers1 = this.tcpClient.getSentHeaders(0);
|
||||
assertThat(headers1.getCommand()).isEqualTo(StompCommand.CONNECT);
|
||||
assertThat(headers1.getSessionId()).isEqualTo(StompBrokerRelayMessageHandler.SYSTEM_SESSION_ID);
|
||||
|
||||
StompHeaderAccessor headers2 = this.tcpClient.getSentHeaders(1);
|
||||
assertThat(headers2.getCommand()).isEqualTo(StompCommand.CONNECT);
|
||||
assertThat(headers2.getSessionId()).isEqualTo("sess1");
|
||||
|
||||
this.brokerRelay.handleMessage(connect);
|
||||
|
||||
assertThat(this.tcpClient.getSentMessages().size()).isEqualTo(2);
|
||||
assertThat(this.outboundChannel.getMessages()).isEmpty();
|
||||
}
|
||||
|
||||
private Message<byte[]> connectMessage(String sessionId, String user) {
|
||||
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
|
||||
headers.setSessionId(sessionId);
|
||||
|
||||
+6
-2
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* 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.
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.springframework.orm.hibernate5;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
@@ -349,7 +350,7 @@ public class LocalSessionFactoryBuilder extends Configuration {
|
||||
Resource[] resources = this.resourcePatternResolver.getResources(pattern);
|
||||
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
|
||||
for (Resource resource : resources) {
|
||||
if (resource.isReadable()) {
|
||||
try {
|
||||
MetadataReader reader = readerFactory.getMetadataReader(resource);
|
||||
String className = reader.getClassMetadata().getClassName();
|
||||
if (matchesEntityTypeFilter(reader, readerFactory)) {
|
||||
@@ -362,6 +363,9 @@ public class LocalSessionFactoryBuilder extends Configuration {
|
||||
packageNames.add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
|
||||
}
|
||||
}
|
||||
catch (FileNotFoundException ex) {
|
||||
// Ignore non-readable resource
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user