Compare commits

...

109 Commits

Author SHA1 Message Date
Spring Builds fcfb16839f Release v5.3.21 2022-06-15 08:13:57 +00:00
Stephane Nicoll c75da7ba10 Upgrade to Reactor 2020.0.20
Closes gh-28612
2022-06-14 19:27:03 +02:00
Sam Brannen eeac150030 Polish contribution
See gh-28616
2022-06-14 16:42:51 +02:00
Fabian Gonzalez 0ce9516aef Avoid eager instantiation of non-singleton FactoryBean in getBeanNamesForType
Closes gh-28616
2022-06-14 16:42:31 +02:00
Sam Brannen e47cc44947 Polish DefaultListableBeanFactoryTests 2022-06-14 16:38:11 +02:00
Juergen Hoeller 57db73dcb8 Upgrade to Tomcat 9.0.64, Jackson 2.12.7, Apache Johnzon 1.2.18, OpenPDF 1.3.28, H2 2.1.212, Mockito 4.6.1, HtmlUnit 2.62, Checkstyle 10.3 2022-06-14 15:10:17 +02:00
Juergen Hoeller d7be1e0dab Polishing 2022-06-14 15:09:39 +02:00
Juergen Hoeller 30c873b4b5 Move NestedServletExceptionTests to spring-web module
See gh-25162
2022-06-14 15:09:21 +02:00
Juergen Hoeller e72b0a04cd Document limitations for MessageProducer/Consumer caching with WebLogic JMS
Closes gh-28500
2022-06-14 15:09:10 +02:00
Juergen Hoeller f8b41c1ad2 Consistent support for setContextClass in CGLIB beans package
Closes gh-28530
2022-06-14 15:08:44 +02:00
rstoyanchev 8c777111fa Revise commit #52d068 with corrected test
Update test detecting RouterFunction beans in parent contexts to use
different bean names and avoid shadowing. Changed the fix accordingly
given that BeanProvider does detect beans in parent contexts.

See gh-28595
2022-06-14 10:07:56 +01:00
rstoyanchev d28d603081 Polishing
See gh-28595
2022-06-14 09:35:17 +01:00
rstoyanchev 52d0681ca1 WebMvc respects RouterFunction beans ordering
Closes gh-28595
2022-06-14 09:20:19 +01:00
Sam Brannen 97854d9fec Refactor ObjectToObjectConverter to use Executable instead of Member 2022-06-13 18:01:54 +02:00
Sam Brannen 73f3860bb7 Polish Javadoc for ObjectToObjectConverter 2022-06-13 18:01:05 +02:00
Sam Brannen 452f1b877c Consider return type of static methods in ObjectToObjectConverter
Prior to this commit, ObjectToObjectConverter considered the return
type of non-static `to[targetType.simpleName]()` methods but did not
consider the return type of static `valueOf(sourceType)`,
`of(sourceType)`, and `from(sourceType)` methods.

This led to scenarios in which `canConvert()` returned `true`, but a
subsequent `convert()` invocation resulted in a
ConverterNotFoundException, which violates the contract of the
converter.

This commit addresses this issue by taking into account the return type
of a static valueOf/of/from factory method when determining if the
ObjectToObjectConverter supports a particular conversion. Whereas the
existing check in `determineToMethod()` ensures that the method return
type is assignable to the `targetType`, the new check in
`determineFactoryMethod()` leniently ensures that the method return
type and `targetType` are "related" (i.e., reside in the same type
hierarchy).

Closes gh-28609
2022-06-13 17:20:18 +02:00
Arjen Poutsma c278d8c656 Do not ignore charset in Jaxb2XmlDecoder
This commit makes sure that the charset, if defined in the mimetype, is
used when decoding XML to JAXB2 objects.

Closes gh-28599
2022-06-13 13:47:31 +02:00
Stephane Nicoll e3b288716d Upgrade to Reactor 2020.0.20
Closes gh-28612
2022-06-13 11:39:15 +02:00
Arjen Poutsma 27738cc20f Fix code samples for nested router functions
Closes gh-28603
2022-06-10 13:36:33 +02:00
Sam Brannen babff8e635 Fix Kotlin example for dependency injection with static factory method
Closes gh-28589
2022-06-09 13:16:19 +02:00
Sam Brannen 290cc73d3d Fix Kotlin example for @Required
Since @Required can only be declared on a method, this commit moves the
@Required declaration from the field to the "set" method.

Closes gh-28590
2022-06-09 13:13:43 +02:00
Stephane Nicoll 8a30bc2993 Upgrade Java 18 version in CI image 2022-06-09 08:14:54 +02:00
Stephane Nicoll aa8be28a01 Upgrade Java 17 version in CI image 2022-06-09 08:14:30 +02:00
Stephane Nicoll f43b28e7ba Upgrade Java 11 version in CI image 2022-06-09 08:14:05 +02:00
Stephane Nicoll 1476867ee7 Upgrade Java 18 version in CI image 2022-06-09 08:13:36 +02:00
Stephane Nicoll 4d9dc61f5d Polish 2022-06-09 08:13:12 +02:00
Stephane Nicoll 7eebc48a6e Upgrade Ubuntu version in CI image 2022-06-09 08:11:36 +02:00
Sam Brannen 8478e8e70a Polish contribution
This commit:

- fixes Checkstyle violations
- improves Javadoc
- adds missing @since tags
- renames getCurrentQueueSize() to getQueueSize()
- avoids NullPointerExceptions in getQueueSize()
- introduces tests for queue size and queue capacity

Closes gh-28583
2022-06-08 16:39:10 +02:00
Rémy e386bdb82c Expose ThreadPoolTaskExecutor queue size and capacity for metrics
We use Grafana to monitor our app via Spring's JMX exporter, and we
think it could be interesting to have at least the current queue size
for this purpose since the queue size directly affects the app memory
load. Having the queue capacity seems also interesting to set up
triggers whose values are calculated based on the maximum capacity of
the queue.

This commit introduces new getCurrentQueueSize() and getQueueCapacity()
methods in ThreadPoolTaskExecutor.

See gh-28583
2022-06-08 16:39:00 +02:00
Arjen Poutsma 4912c3c455 Updated sdkmanrc 2022-06-08 12:13:21 +02:00
rstoyanchev 8fcc7ab9d1 CompositeLog respects log level changes at runtime
Closes gh-28477
2022-06-08 10:07:52 +01:00
rstoyanchev 7c47b470ff MockMvc allows HttpMethod input for multipart request
Closes gh-28545
2022-06-08 10:07:52 +01:00
Sam Brannen 479ef3f3fd Update documentation regarding nested test class support
Closes gh-28579
2022-06-08 09:52:42 +02:00
Sam Brannen be1b7da12f Add entries for "Sam Brannen" to .mailmap 2022-06-07 14:27:42 +02:00
Phillip Webb 89360b18f4 Update '.mailmap` to consistently use @vmware.com emails
(cherry picked from commit 83063a7269)
2022-06-07 14:14:10 +02:00
Stephane Nicoll 209fe5f452 Merge pull request #28572 from gorisanson
* pr/28572:
  Polish contribution
  Update reference docs to use PropertySourcesPlaceholderConfigurer

Closes gh-28572
2022-06-07 08:30:52 +02:00
Stephane Nicoll e18a118f8b Polish contribution
See gh-28572
2022-06-07 08:29:28 +02:00
Lee, Kyutae 77aac7768d Update reference docs to use PropertySourcesPlaceholderConfigurer
See gh-28572
2022-06-07 08:22:53 +02:00
Sam Brannen e2767371b5 Lazily initialize DataSize.PATTERN
To avoid unnecessary eager initialization of DataSize.PATTERN, this
commit initializes it lazily in the first invocation of DataSize.parse
by moving PATTERN to a private static nested class.

Closes gh-28560
2022-06-03 13:30:45 +02:00
Sam Brannen aab9da0366 Polish LocaleResolver support 2022-06-03 13:10:55 +02:00
Sam Brannen cda1e5507c Polishing 2022-06-01 16:28:05 +02:00
Balázs Póka 1d5ffaf30a Always construct new exception on error in DefaultWebClient
Always construct new exception on error, otherwise memory leak may
occur due to repeated use of singleton exception.

Closes gh-28550
2022-06-01 16:07:41 +02:00
Arjen Poutsma c55606ed08 Recognize Kotlin coroutines in isAsyncVoidReturnType
This commit makes sure that Kotlin coroutines are correctly identified
by InvocableHandlerMethod::isAsyncVoidReturnType.

Closes gh-26829
2022-06-01 15:13:30 +02:00
Sam Brannen aa8802a81d Avoid new AssertJ deprecations 2022-05-31 16:13:31 +02:00
Sam Brannen 1beb7068f6 Use new AssertJ exception assertions 2022-05-31 14:08:28 +02:00
Sam Brannen 9d324e59a0 Upgrade to AssertJ 3.23.0 2022-05-31 12:55:43 +02:00
Sam Brannen 8547f8601d Polish LocaleResolver tests 2022-05-31 11:55:30 +02:00
Stephane Nicoll 40cb81470b Merge pull request #28542 from eltociear
* pr/28542:
  Fix typo in webflux.adoc

Closes gh-28542
2022-05-31 10:01:30 +02:00
Ikko Ashimine 6e3b3c5419 Fix typo in webflux.adoc
See gh-28542
2022-05-31 10:01:13 +02:00
Sam Brannen a221835558 Throw IllegalStateException for invalid port in HierarchicalUriComponents
Prior to this commit, getPort() in HierarchicalUriComponents threw a
NumberFormatException for an invalid port supplied as a String, which
was inconsistent with exception handling elsewhere in the class as well
as within the same method.

This commit introduces a try-catch block in getPort() to consistently
throw IllegalStateExceptions for ports that cannot be parsed.

Closes gh-28521
2022-05-25 11:29:12 +02:00
Sam Brannen aa06a09dee Polishing 2022-05-25 11:29:12 +02:00
hsteinmueller bde0931e51 Fix Javadoc for DatabaseClient
The documentation for DatabaseClient had misplaced double quotes in the
example on how to map a select statement to a row.

Closes gh-28520
2022-05-24 17:15:44 +02:00
Sam Brannen 7b95c928d1 Fix Javadoc for ResourcePatternResolver 2022-05-23 20:32:01 +02:00
Sam Brannen 53f88d455f Fix Javadoc for AbstractFileResolvingResource.isFile(URI) 2022-05-23 20:32:01 +02:00
Sam Brannen 53a506f6bb Polishing 2022-05-23 20:22:37 +02:00
rstoyanchev f95bf96ec9 Correct path encoding/decoding in PathResourceResolver
Decoding is required for non-UrlResource when the HandlerMapping is
not expected to decode the path. Encoding is the opposite.

This commit ensures correct determination of whether the HandlerMapping
is expected to have decoded the path or not that in turn depends on
whether PathPattern or PathMatcher is in use.

Closes gh-27791
2022-05-23 11:03:42 +01:00
rstoyanchev 66a5742df3 Polishing 2022-05-23 10:07:03 +01:00
Sam Brannen 59c7bb1f86 Use Arrays.toString instead of Arrays.asList when generating Strings 2022-05-17 15:36:31 +02:00
Sam Brannen a1c3efbb5f Polish ManagedList[Tests] and ManagedSet[Tests] 2022-05-17 15:36:31 +02:00
Sam Brannen 6efe3aee34 Polishing 2022-05-16 11:20:20 +02:00
Sam Brannen f2fe7f335c Improve nullReturningBeanPostProcessor() test
See gh-28459
2022-05-14 18:30:39 +02:00
Sam Brannen 48c797e429 Fix Kotlin example for static factory method
Closes gh-28399
2022-05-11 17:33:31 +02:00
Sam Brannen be782a2197 Polish ref docs regarding the BeanFactory API
See gh-28403
2022-05-11 17:16:40 +02:00
Sam Brannen 8098e45bad Sync gradle.properties between 5.3.x and main 2022-05-11 16:30:44 +02:00
Sam Brannen 06679a5583 Fix tests in DispatcherServletTests
See gh-28424
2022-05-11 16:00:26 +02:00
Sam Brannen 745eb1a881 Polish DispatcherServletTests 2022-05-11 15:59:47 +02:00
Spring Builds 10c55ff912 Next development version (v5.3.21-SNAPSHOT) 2022-05-11 07:08:24 +00:00
Juergen Hoeller 83186b689f Refine CachedIntrospectionResults property introspection
Closes gh-28445
2022-05-11 08:32:06 +02:00
rstoyanchev dc2947c52d Ignore invalid connect frame
Closes gh-28443
2022-05-11 07:22:22 +01:00
Arjen Poutsma e4ec376075 Disabling Undertow server in CoroutinesIntegrationTests 2022-05-10 15:55:00 +02:00
Juergen Hoeller c81e11d537 Polishing 2022-05-10 13:07:00 +02:00
Juergen Hoeller de6180b093 Upgrade to Reactor 2020.0.19
Includes Netty 4.1.77 and RxJava 3.1.4.

Closes gh-28437
2022-05-10 13:05:56 +02:00
Sam Brannen 1c10cdd1e8 Update copyright dates
See gh-28433
2022-05-10 11:33:32 +02:00
evgeny.bovykin 941b92cbed Make inner classes static when feasible
A static nested class does not keep an implicit reference to its
enclosing instance.

This prevents a common cause of memory leaks and uses less memory per
instance of the class.

Closes gh-28433
2022-05-10 11:32:37 +02:00
Sam Brannen e26d8839b3 Stop referring to features as Java 6/7 features where unnecessary 2022-05-09 19:09:06 +02:00
Sam Brannen a1c7380398 Add test for value attribute in @ModelAttribute in WebFlux
This complements the previous commit which tested only the `name`
attribute.

See gh-28423
2022-05-09 15:22:22 +02:00
Sam Brannen 7dd622bdb2 Support name attribute in @ModelAttribute in WebFlux
Prior to this commit, the `name` attribute in @ModelAttribute was not
supported when using WebFlux. This is because MethodParameter was used
instead of SynthesizingMethodParameter when retrieving the
@ModelAttribute annotation. In other words, @AliasFor was not honored
because the annotation was not synthesized. Consequently, only the
`value` attribute was supported in WebFlux when specifying a custom name
via @ModelAttribute.

This commit fixes this by using SynthesizingMethodParameter to retrieve
the @ModelAttribute annotation.

Closes gh-28423
2022-05-07 17:16:26 +02:00
Sam Brannen 64c96c579d Polish contribution
See gh-28422
2022-05-07 16:18:47 +02:00
Carlos Bouzón García 39e3876301 Fix BindingResult error when ModelAttribute has custom name in WebFlux
Closes gh-28422
2022-05-07 16:18:04 +02:00
Juergen Hoeller f771603789 Polishing 2022-05-05 18:04:54 +02:00
Juergen Hoeller e441832e99 Accept WritableResource as required dependency type as well
Closes gh-15284
2022-05-05 18:04:13 +02:00
Juergen Hoeller f963fc5f98 Check that nullable annotations are from org.springframework.lang
Closes gh-28410
2022-05-05 18:02:27 +02:00
Juergen Hoeller b55eee1b0d Upgrade to ASM 9.3
Closes gh-28390
2022-05-05 18:01:53 +02:00
Juergen Hoeller 28742171fd Upgrade to Netty 4.1.76, Mockito 4.5.1, HtmlUnit 2.61 2022-05-05 18:01:31 +02:00
Lee, Kyutae 7a75b94556 Fix typo in reference docs regarding RequestMappingHandlerAdapter
Closes gh-28370
2022-05-05 16:31:40 +02:00
Sam Brannen ab71ff93bb Polish package-info for org.springframework.util
See gh-28411
2022-05-05 16:22:52 +02:00
neals cf30327740 Remove Log4J configurer from package-info.java in spring-core
Closes gh-28411
2022-05-05 16:16:49 +02:00
neals e22a038725 Remove Log4J initialization from package-info.java
Closes gh-28420
2022-05-05 16:10:59 +02:00
Brian Clozel 7aedb9ee33 Build CI image using oci-build-task resource 2022-05-03 15:50:29 +02:00
Brian Clozel 5b1719cd77 Upgrade CI to concourse-release-scripts 0.3.4 2022-05-03 15:09:23 +02:00
Brian Clozel c056b81753 Upgrade JDK and Ubuntu versions in CI image 2022-05-03 15:08:14 +02:00
Brian Clozel dbdd67ec62 Remove outdated docker-image resource from CI
The docker-image resource is now replaced by the registry-image
resource.
2022-05-03 15:05:58 +02:00
Sam Brannen 4fcfa5b991 Update and simplify ArrayConstructorTests 2022-05-03 14:27:48 +02:00
Sam Brannen ed06a6de26 Convert SimpleFormController example to @Controller in reference manual
This change is necessary since the SimpleFormController class no longer
exists.
2022-05-03 12:03:04 +02:00
Sam Brannen afa799b4f0 Suppress warning in test 2022-05-03 11:46:47 +02:00
rstoyanchev f0d149b330 Polishing contribution
Closes gh-27830
2022-04-28 11:26:50 +01:00
binchoo caaf83b8e6 Add tests for binding to a Part field
See gh-27830
2022-04-28 10:45:09 +01:00
rstoyanchev b30f4d7bb7 Exposes all root causes to ExceptionHandler methods
Closes gh-28155
2022-04-28 04:04:57 +01:00
Arjen Poutsma b6b03f38d7 Updated .sdkmanrc 2022-04-26 11:54:02 +02:00
Stephane Nicoll 46b0d7dc03 Merge pull request #28369 from izeye
* pr/28369:
  Add Javadoc since for GraphQL constants

Closes gh-28369
2022-04-24 10:05:28 +02:00
izeye fcf64798b5 Add Javadoc since for GraphQL constants
See gh-28369
2022-04-24 09:58:50 +02:00
Stephane Nicoll 94ed07d9cb Merge pull request #28372 from zhangmingqi09
* pr/28372:
  Update copyright year of changed file
  Fix github issue reference in RequestMappingHandlerMapping

Closes gh-28372
2022-04-24 09:57:02 +02:00
Stephane Nicoll b81c62d064 Update copyright year of changed file
See gh-28372
2022-04-24 09:56:39 +02:00
zhangmingqi09 ca1a11acac Fix github issue reference in RequestMappingHandlerMapping
See gh-28372
2022-04-24 09:55:20 +02:00
Stephane Nicoll c261d40610 Merge pull request #28340 from koenpunt
* pr/28340:
  Update copyright year of changed file
  Fix method reference in Kotlin documentation

Closes gh-28340
2022-04-14 14:11:28 +02:00
Stephane Nicoll 3017955eff Update copyright year of changed file
See gh-28340
2022-04-14 14:09:54 +02:00
Koen Punt 22c82ff206 Fix method reference in Kotlin documentation
See gh-28340
2022-04-14 14:09:02 +02:00
Jerome Prinet f54952481b Update Gradle Enterprise plugin to 3.9
Closes gh-28338
2022-04-14 11:04:22 +02:00
Spring Builds 9e733b09e2 Next development version (v5.3.20-SNAPSHOT) 2022-04-13 09:24:33 +00:00
222 changed files with 3832 additions and 2324 deletions
+32 -22
View File
@@ -1,23 +1,33 @@
Juergen Hoeller <jhoeller@pivotal.io> jhoeller <jhoeller@vmware.com>
<jhoeller@pivotal.io> <jhoeller@vmware.com>
<jhoeller@pivotal.io> <jhoeller@gopivotal.com>
<rstoyanchev@pivotal.io> <rstoyanchev@vmware.com>
<rstoyanchev@pivotal.io> <rstoyanchev@gopivotal.com>
<pwebb@pivotal.io> <pwebb@vmware.com>
<pwebb@pivotal.io> <pwebb@gopivotal.com>
<cbeams@pivotal.io> <cbeams@vmware.com>
<cbeams@pivotal.io> <cbeams@gopivotal.com>
<cbeams@pivotal.io> <cbeams@gmail.com>
<apoutsma@pivotal.io> <apoutsma@vmware.com>
<apoutsma@pivotal.io> <apoutsma@gopivotal.com>
<apoutsma@pivotal.io> <poutsma@mac.com>
<ogierke@pivotal.io> <ogierke@vmware.com>
<ogierke@pivotal.io> <ogierke@gopivotal.com>
<dsyer@pivotal.io> <dsyer@vmware.com>
<dsyer@pivotal.io> <dsyer@gopivotal.com>
<dsyer@pivotal.io> <david_syer@hotmail.com>
<aclement@pivotal.io> <aclement@vmware.com>
<aclement@pivotal.io> <aclement@gopivotal.com>
<aclement@pivotal.io> <andrew.clement@gmail.com>
Juergen Hoeller <jhoeller@vmware.com>
Juergen Hoeller <jhoeller@vmware.com> <jhoeller@pivotal.io>
Juergen Hoeller <jhoeller@vmware.com> <jhoeller@gopivotal.com>
Rossen Stoyanchev <rstoyanchev@vmware.com>
Rossen Stoyanchev <rstoyanchev@vmware.com> <rstoyanchev@pivotal.io>
Rossen Stoyanchev <rstoyanchev@vmware.com> <rstoyanchev@gopivotal.com>
Phillip Webb <pwebb@vmware.com>
Phillip Webb <pwebb@vmware.com> <pwebb@pivotal.io>
Phillip Webb <pwebb@vmware.com> <pwebb@gopivotal.com>
Chris Beams <cbeams@vmware.com>
Chris Beams <cbeams@vmware.com> <cbeams@pivotal.io>
Chris Beams <cbeams@vmware.com> <cbeams@gopivotal.com>
Arjen Poutsma <apoutsma@vmware.com>
Arjen Poutsma <apoutsma@vmware.com> <apoutsma@pivotal.io>
Arjen Poutsma <apoutsma@vmware.com> <apoutsma@gopivotal.com>
Arjen Poutsma <apoutsma@vmware.com> <poutsma@mac.com>
Oliver Drotbohm <odrotbohm@vmware.com>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@vmware.com>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@pivotal.io>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@gopivotal.com>
Dave Syer <dsyer@vmware.com>
Dave Syer <dsyer@vmware.com> <dsyer@pivotal.io>
Dave Syer <dsyer@vmware.com> <dsyer@gopivotal.com>
Dave Syer <dsyer@vmware.com> <david_syer@hotmail.com>
Andy Clement <aclement@vmware.com>
Andy Clement <aclement@vmware.com> <aclement@pivotal.io>
Andy Clement <aclement@vmware.com> <aclement@gopivotal.com>
Andy Clement <aclement@vmware.com> <andrew.clement@gmail.com>
Sam Brannen <sbrannen@vmware.com>
Sam Brannen <sbrannen@vmware.com> <sbrannen@pivotal.io>
Sam Brannen <sbrannen@vmware.com> <sam@sambrannen.com>
<dmitry.katsubo@gmail.com> <dmitry.katsubo@gmai.com>
Nick Williams <nicholas@nicholaswilliams.net> Nicholas Williams <nicholas@nicholaswilliams.net>
Nick Williams <nicholas@nicholaswilliams.net>
+1 -1
View File
@@ -1,3 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=8.0.322-librca
java=8.0.333-librca
+14 -14
View File
@@ -27,9 +27,9 @@ configure(allprojects) { project ->
dependencyManagement {
imports {
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.6"
mavenBom "io.netty:netty-bom:4.1.75.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.18"
mavenBom "com.fasterxml.jackson:jackson-bom:2.12.7"
mavenBom "io.netty:netty-bom:4.1.77.Final"
mavenBom "io.projectreactor:reactor-bom:2020.0.20"
mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR13"
mavenBom "io.rsocket:rsocket-bom:1.1.2"
mavenBom "org.eclipse.jetty:jetty-bom:9.4.46.v20220331"
@@ -67,7 +67,7 @@ configure(allprojects) { project ->
dependency "io.reactivex:rxjava:1.3.8"
dependency "io.reactivex:rxjava-reactive-streams:1.2.1"
dependency "io.reactivex.rxjava2:rxjava:2.2.21"
dependency "io.reactivex.rxjava3:rxjava:3.1.3"
dependency "io.reactivex.rxjava3:rxjava:3.1.4"
dependency "io.smallrye.reactive:mutiny:1.4.0"
dependency "io.projectreactor.tools:blockhound:1.0.6.RELEASE"
@@ -83,7 +83,7 @@ configure(allprojects) { project ->
exclude group: "xpp3", name: "xpp3_min"
exclude group: "xmlpull", name: "xmlpull"
}
dependency "org.apache.johnzon:johnzon-jsonb:1.2.16"
dependency "org.apache.johnzon:johnzon-jsonb:1.2.18"
dependency("org.codehaus.jettison:jettison:1.3.8") {
exclude group: "stax", name: "stax-api"
}
@@ -94,9 +94,9 @@ configure(allprojects) { project ->
dependency "org.ogce:xpp3:1.1.6"
dependency "org.yaml:snakeyaml:1.30"
dependency "com.h2database:h2:2.1.210"
dependency "com.h2database:h2:2.1.212"
dependency "com.github.ben-manes.caffeine:caffeine:2.9.3"
dependency "com.github.librepdf:openpdf:1.3.27"
dependency "com.github.librepdf:openpdf:1.3.28"
dependency "com.rometools:rome:1.18.0"
dependency "commons-io:commons-io:2.5"
dependency "io.vavr:vavr:0.10.4"
@@ -128,14 +128,14 @@ configure(allprojects) { project ->
dependency "org.webjars:webjars-locator-core:0.48"
dependency "org.webjars:underscorejs:1.8.3"
dependencySet(group: 'org.apache.tomcat', version: '9.0.62') {
dependencySet(group: 'org.apache.tomcat', version: '9.0.64') {
entry 'tomcat-util'
entry('tomcat-websocket') {
exclude group: "org.apache.tomcat", name: "tomcat-servlet-api"
exclude group: "org.apache.tomcat", name: "tomcat-websocket-api"
}
}
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.62') {
dependencySet(group: 'org.apache.tomcat.embed', version: '9.0.64') {
entry 'tomcat-embed-core'
entry 'tomcat-embed-websocket'
}
@@ -191,14 +191,14 @@ configure(allprojects) { project ->
dependency "org.junit.support:testng-engine:1.0.1"
dependency "org.hamcrest:hamcrest:2.1"
dependency "org.awaitility:awaitility:3.1.6"
dependency "org.assertj:assertj-core:3.22.0"
dependency "org.assertj:assertj-core:3.23.0"
dependencySet(group: 'org.xmlunit', version: '2.9.0') {
entry 'xmlunit-assertj'
entry('xmlunit-matchers') {
exclude group: "org.hamcrest", name: "hamcrest-core"
}
}
dependencySet(group: 'org.mockito', version: '4.4.0') {
dependencySet(group: 'org.mockito', version: '4.6.1') {
entry('mockito-core') {
exclude group: "org.hamcrest", name: "hamcrest-core"
}
@@ -206,10 +206,10 @@ configure(allprojects) { project ->
}
dependency "io.mockk:mockk:1.12.1"
dependency("net.sourceforge.htmlunit:htmlunit:2.60.0") {
dependency("net.sourceforge.htmlunit:htmlunit:2.62.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:htmlunit-driver:2.60.0") {
dependency("org.seleniumhq.selenium:htmlunit-driver:2.62.0") {
exclude group: "commons-logging", name: "commons-logging"
}
dependency("org.seleniumhq.selenium:selenium-java:3.141.59") {
@@ -340,7 +340,7 @@ configure([rootProject] + javaProjects) { project ->
}
checkstyle {
toolVersion = "10.1"
toolVersion = "10.3"
configDirectory.set(rootProject.file("src/checkstyle"))
}
+1 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:focal-20220404
FROM ubuntu:focal-20220531
ADD setup.sh /setup.sh
ADD get-jdk-url.sh /get-jdk-url.sh
+9 -9
View File
@@ -3,18 +3,18 @@ set -e
case "$1" in
java8)
echo "https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u322-b06/OpenJDK8U-jdk_x64_linux_hotspot_8u322b06.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/8u333+2/bellsoft-jdk8u333+2-linux-amd64.tar.gz"
;;
java11)
echo "https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.14.1%2B1/OpenJDK11U-jdk_x64_linux_hotspot_11.0.14.1_1.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/11.0.15.1+2/bellsoft-jdk11.0.15.1+2-linux-amd64.tar.gz"
;;
java17)
echo "https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.2%2B8/OpenJDK17U-jdk_x64_linux_hotspot_17.0.2_8.tar.gz"
;;
java18)
echo "https://github.com/adoptium/temurin18-binaries/releases/download/jdk-18%2B36/OpenJDK18U-jdk_x64_linux_hotspot_18_36.tar.gz"
;;
*)
java17)
echo "https://github.com/bell-sw/Liberica/releases/download/17.0.3.1+2/bellsoft-jdk17.0.3.1+2-linux-amd64.tar.gz"
;;
java18)
echo "https://github.com/bell-sw/Liberica/releases/download/18.0.1.1+2/bellsoft-jdk18.0.1.1+2-linux-amd64.tar.gz"
;;
*)
echo $"Unknown java version"
exit 1
esac
-2
View File
@@ -14,8 +14,6 @@ rm -rf /var/lib/apt/lists/*
curl https://raw.githubusercontent.com/spring-io/concourse-java-scripts/v0.0.4/concourse-java.sh > /opt/concourse-java.sh
curl --output /opt/concourse-release-scripts.jar https://repo.spring.io/release/io/spring/concourse/releasescripts/concourse-release-scripts/0.3.2/concourse-release-scripts-0.3.2.jar
###########################################################
# JAVA
###########################################################
+4
View File
@@ -1,5 +1,6 @@
github-repo: "https://github.com/spring-projects/spring-framework.git"
github-repo-name: "spring-projects/spring-framework"
sonatype-staging-profile: "org.springframework"
docker-hub-organization: "springci"
artifactory-server: "https://repo.spring.io"
branch: "5.3.x"
@@ -7,4 +8,7 @@ milestone: "5.3.x"
build-name: "spring-framework"
pipeline-name: "spring-framework"
concourse-url: "https://ci.spring.io"
registry-mirror-host: docker.repo.spring.io
registry-mirror-username: ((artifactory-username))
registry-mirror-password: ((artifactory-password))
task-timeout: 1h00m
+18 -10
View File
@@ -12,7 +12,7 @@ anchors:
SONATYPE_USERNAME: ((sonatype-username))
SONATYPE_PASSWORD: ((sonatype-password))
SONATYPE_URL: ((sonatype-url))
SONATYPE_STAGING_PROFILE_ID: ((sonatype-staging-profile-id))
SONATYPE_STAGING_PROFILE: ((sonatype-staging-profile))
artifactory-task-params: &artifactory-task-params
ARTIFACTORY_SERVER: ((artifactory-server))
ARTIFACTORY_USERNAME: ((artifactory-username))
@@ -24,6 +24,10 @@ anchors:
username: ((docker-hub-username))
password: ((docker-hub-password))
tag: ((milestone))
registry-mirror-vars: &registry-mirror-vars
registry-mirror-host: ((registry-mirror-host))
registry-mirror-username: ((registry-mirror-username))
registry-mirror-password: ((registry-mirror-password))
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!>
@@ -92,7 +96,7 @@ resources:
branch: ((branch))
paths: ["ci/images/*"]
- name: ci-image
type: docker-image
type: registry-image
icon: docker
source:
<<: *docker-resource-source
@@ -162,13 +166,20 @@ resources:
jobs:
- name: build-ci-images
plan:
- get: ci-images-git-repo
trigger: true
- in_parallel:
- get: git-repo
- get: ci-images-git-repo
trigger: true
- task: build-ci-image
privileged: true
file: git-repo/ci/tasks/build-ci-image.yml
output_mapping:
image: ci-image
vars:
ci-image-name: ci-image
<<: *registry-mirror-vars
- put: ci-image
params:
build: ci-images-git-repo/ci/images
dockerfile: ci-images-git-repo/ci/images/ci-image/Dockerfile
image: ci-image/image.tar
- name: build
serial: true
public: true
@@ -345,7 +356,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
@@ -390,7 +400,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
@@ -435,7 +444,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
+2 -2
View File
@@ -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; }
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash
export BUILD_INFO_LOCATION=$(pwd)/artifactory-repo/build-info.json
version=$( cat artifactory-repo/build-info.json | jq -r '.buildInfo.modules[0].id' | sed 's/.*:.*:\(.*\)/\1/' )
java -jar /opt/concourse-release-scripts.jar syncToCentral "RELEASE" $BUILD_INFO_LOCATION || { exit 1; }
echo "Sync complete"
echo $version > version/version
+31
View File
@@ -0,0 +1,31 @@
---
platform: linux
image_resource:
type: registry-image
source:
repository: concourse/oci-build-task
tag: 0.9.1
registry_mirror:
host: ((registry-mirror-host))
username: ((registry-mirror-username))
password: ((registry-mirror-password))
inputs:
- name: ci-images-git-repo
outputs:
- name: image
caches:
- path: ci-image-cache
params:
CONTEXT: ci-images-git-repo/ci/images
DOCKERFILE: ci-images-git-repo/ci/images/ci-image/Dockerfile
DOCKER_HUB_AUTH: ((docker-hub-auth))
run:
path: /bin/sh
args:
- "-c"
- |
mkdir -p /root/.docker
cat > /root/.docker/config.json <<EOF
{ "auths": { "https://index.docker.io/v1/": { "auth": "$DOCKER_HUB_AUTH" }}}
EOF
build
+6 -1
View File
@@ -1,5 +1,10 @@
---
platform: linux
image_resource:
type: registry-image
source:
repository: springio/concourse-release-scripts
tag: '0.3.4'
inputs:
- name: git-repo
- name: artifactory-repo
@@ -13,6 +18,6 @@ params:
SONATYPE_USER:
SONATYPE_PASSWORD:
SONATYPE_URL:
SONATYPE_STAGING_PROFILE_ID:
SONATYPE_STAGING_PROFILE:
run:
path: git-repo/ci/scripts/promote-version.sh
+3 -3
View File
@@ -1,5 +1,5 @@
version=5.3.19-SNAPSHOT
org.gradle.jvmargs=-Xmx1536M
version=5.3.21
org.gradle.jvmargs=-Xmx2048m
org.gradle.caching=true
org.gradle.parallel=true
kotlin.stdlib.default.dependency=false
kotlin.stdlib.default.dependency=false
@@ -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.
@@ -28,7 +28,7 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatException;
/**
* Integration tests for advice invocation order for advice configured via the
@@ -52,7 +52,7 @@ class AopNamespaceHandlerAdviceOrderIntegrationTests {
assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after", "after returning");
aspect.invocations.clear();
assertThatExceptionOfType(Exception.class).isThrownBy(() -> echo.echo(new Exception()));
assertThatException().isThrownBy(() -> echo.echo(new Exception()));
assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after", "after throwing");
}
}
@@ -69,7 +69,7 @@ class AopNamespaceHandlerAdviceOrderIntegrationTests {
assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after returning", "after");
aspect.invocations.clear();
assertThatExceptionOfType(Exception.class).isThrownBy(() -> echo.echo(new Exception()));
assertThatException().isThrownBy(() -> echo.echo(new Exception()));
assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after throwing", "after");
}
}
@@ -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.
@@ -38,7 +38,7 @@ import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatException;
/**
* Integration tests for advice invocation order for advice configured via
@@ -65,8 +65,7 @@ class AspectJAutoProxyAdviceOrderIntegrationTests {
assertThat(aspect.invocations).containsExactly("around - start", "before", "after returning", "after", "around - end");
aspect.invocations.clear();
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> echo.echo(new Exception()));
assertThatException().isThrownBy(() -> echo.echo(new Exception()));
assertThat(aspect.invocations).containsExactly("around - start", "before", "after throwing", "after", "around - end");
}
}
@@ -95,8 +94,7 @@ class AspectJAutoProxyAdviceOrderIntegrationTests {
assertThat(aspect.invocations).containsExactly("around - start", "before", "after returning", "after", "around - end");
aspect.invocations.clear();
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> echo.echo(new Exception()));
assertThatException().isThrownBy(() -> echo.echo(new Exception()));
assertThat(aspect.invocations).containsExactly("around - start", "before", "after throwing", "after", "around - end");
}
}
@@ -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.
@@ -34,7 +34,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatException;
/**
* Integration tests for the @EnableCaching annotation.
@@ -62,8 +62,7 @@ class EnableCachingIntegrationTests {
// this test is a bit fragile, but gets the job done, proving that an
// attempt was made to look up the AJ aspect. It's due to classpath issues
// in .integration-tests that it's not found.
assertThatExceptionOfType(Exception.class).isThrownBy(
ctx::refresh)
assertThatException().isThrownBy(ctx::refresh)
.withMessageContaining("AspectJCachingConfiguration");
}
@@ -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.
@@ -45,7 +45,7 @@ import org.springframework.transaction.interceptor.BeanFactoryTransactionAttribu
import org.springframework.transaction.testfixture.CallCountingTransactionManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatException;
/**
* Integration tests for the @EnableTransactionManagement annotation.
@@ -98,7 +98,7 @@ class EnableTransactionManagementIntegrationTests {
// this test is a bit fragile, but gets the job done, proving that an
// attempt was made to look up the AJ aspect. It's due to classpath issues
// in .integration-tests that it's not found.
assertThatExceptionOfType(Exception.class)
assertThatException()
.isThrownBy(ctx::refresh)
.withMessageContaining("AspectJJtaTransactionManagementConfiguration");
}
+1 -1
View File
@@ -7,7 +7,7 @@ pluginManagement {
}
plugins {
id "com.gradle.enterprise" version "3.8.1"
id "com.gradle.enterprise" version "3.9"
id "io.spring.ge.conventions" version "0.0.9"
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -378,7 +378,7 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to evaluate join point for arguments " + Arrays.asList(args) +
logger.debug("Failed to evaluate join point for arguments " + Arrays.toString(args) +
" - falling back to non-match", ex);
}
return false;
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -424,7 +424,7 @@ public class ProxyFactoryBean extends ProxyCreatorSupport
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));
"- cannot resolve interceptor names " + Arrays.toString(this.interceptorNames));
}
// Globals can't be last unless we specified a targetSource using the property...
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -44,7 +44,7 @@ import org.springframework.core.annotation.Order;
import org.springframework.core.testfixture.TimeStamped;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* Also tests AdvisedSupport and ProxyCreatorSupport superclasses.
@@ -277,7 +277,7 @@ public class ProxyFactoryTests {
assertThat(config.getAdvisors().length == oldCount).isTrue();
assertThatExceptionOfType(RuntimeException.class)
assertThatRuntimeException()
.as("Existing object won't implement this interface any more")
.isThrownBy(ts::getTimeStamp); // Existing reference will fail
@@ -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.
@@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.aop.testfixture.advice.MyThrowsHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
@@ -63,9 +64,7 @@ public class ThrowsAdviceInterceptorTests {
Exception ex = new Exception();
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willThrow(ex);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
ti.invoke(mi))
.isSameAs(ex);
assertThatException().isThrownBy(() -> ti.invoke(mi)).isSameAs(ex);
assertThat(th.getCalls()).isEqualTo(0);
}
@@ -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.
@@ -22,7 +22,9 @@ import org.junit.jupiter.api.Test;
import org.springframework.transaction.testfixture.CallCountingTransactionManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Rod Johnson
@@ -104,44 +106,44 @@ public class TransactionAspectTests {
@Test
public void defaultCommitOnAnnotatedClass() throws Throwable {
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false))
assertThatException()
.isThrownBy(() -> testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), false))
.isSameAs(ex);
}
@Test
public void defaultRollbackOnAnnotatedClass() throws Throwable {
RuntimeException ex = new RuntimeException();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true))
assertThatRuntimeException()
.isThrownBy(() -> testRollback(() -> annotationOnlyOnClassWithNoInterface.echo(ex), true))
.isSameAs(ex);
}
@Test
public void defaultCommitOnSubclassOfAnnotatedClass() throws Throwable {
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false))
assertThatException()
.isThrownBy(() -> testRollback(() -> new SubclassOfClassWithTransactionalAnnotation().echo(ex), false))
.isSameAs(ex);
}
@Test
public void defaultCommitOnSubclassOfClassWithTransactionalMethodAnnotated() throws Throwable {
Exception ex = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false))
assertThatException()
.isThrownBy(() -> testRollback(() -> new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex), false))
.isSameAs(ex);
}
@Test
public void noCommitOnImplementationOfAnnotatedInterface() throws Throwable {
final Exception ex = new Exception();
Exception ex = new Exception();
testNotTransactional(() -> new ImplementsAnnotatedInterface().echo(ex), ex);
}
@Test
public void noRollbackOnImplementationOfAnnotatedInterface() throws Throwable {
final Exception rollbackProvokingException = new RuntimeException();
Exception rollbackProvokingException = new RuntimeException();
testNotTransactional(() -> new ImplementsAnnotatedInterface().echo(rollbackProvokingException),
rollbackProvokingException);
}
@@ -165,8 +167,9 @@ public class TransactionAspectTests {
protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable {
txManager.clear();
assertThat(txManager.begun).isEqualTo(0);
assertThatExceptionOfType(Throwable.class).isThrownBy(
toc::performTransactionalOperation).isSameAs(expected);
assertThatExceptionOfType(Throwable.class)
.isThrownBy(toc::performTransactionalOperation)
.isSameAs(expected);
assertThat(txManager.begun).isEqualTo(0);
}
@@ -22,6 +22,7 @@ import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.HashSet;
@@ -292,10 +293,12 @@ public final class CachedIntrospectionResults {
// Only allow all name variants of Class properties
continue;
}
if (pd.getWriteMethod() == null && pd.getPropertyType() != null &&
(ClassLoader.class.isAssignableFrom(pd.getPropertyType()) ||
ProtectionDomain.class.isAssignableFrom(pd.getPropertyType()))) {
// Ignore ClassLoader and ProtectionDomain read-only properties - no need to bind to those
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()) {
@@ -344,10 +347,8 @@ 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 && pd.getPropertyType() != null &&
(ClassLoader.class.isAssignableFrom(pd.getPropertyType()) ||
ProtectionDomain.class.isAssignableFrom(pd.getPropertyType()))) {
// Ignore ClassLoader and ProtectionDomain read-only properties - no need to bind to those
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);
@@ -379,8 +380,7 @@ public final class CachedIntrospectionResults {
if (Modifier.isStatic(method.getModifiers()) ||
method.getDeclaringClass() == Object.class || method.getDeclaringClass() == Class.class ||
method.getParameterCount() > 0 || method.getReturnType() == void.class ||
ClassLoader.class.isAssignableFrom(method.getReturnType()) ||
ProtectionDomain.class.isAssignableFrom(method.getReturnType())) {
isInvalidReadOnlyPropertyType(method.getReturnType())) {
return false;
}
try {
@@ -393,6 +393,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;
@@ -1,5 +1,5 @@
/**
* Support package for the Java 6 ServiceLoader facility.
* Support package for the Java {@link java.util.ServiceLoader} facility.
*/
@NonNullApi
@NonNullFields
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -985,7 +985,7 @@ class ConstructorResolver {
/**
* Delegate for checking Java 6's {@link ConstructorProperties} annotation.
* Delegate for checking Java's {@link ConstructorProperties} annotation.
*/
private static class ConstructorPropertiesChecker {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -585,7 +585,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (!matchFound) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
}
if (matchFound) {
@@ -17,7 +17,7 @@
package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.BeanMetadataElement;
@@ -31,6 +31,8 @@ import org.springframework.lang.Nullable;
* @author Rod Johnson
* @author Rob Harrop
* @author Juergen Hoeller
* @author Stephane Nicoll
* @author Sam Brannen
* @since 27.05.2003
* @param <E> the element type
*/
@@ -55,16 +57,16 @@ public class ManagedList<E> extends ArrayList<E> implements Mergeable, BeanMetad
/**
* Return a new instance containing an arbitrary number of elements.
* Create a new instance containing an arbitrary number of elements.
* @param elements the elements to be contained in the list
* @param <E> the {@code List}'s element type
* @return a {@code List} containing the specified elements
* @return a {@code ManagedList} containing the specified elements
* @since 5.3.16
*/
@SuppressWarnings("unchecked")
@SafeVarargs
public static <E> ManagedList<E> of(E... elements) {
ManagedList<E> list = new ManagedList<>();
list.addAll(Arrays.asList(elements));
Collections.addAll(list, elements);
return list;
}
@@ -16,7 +16,7 @@
package org.springframework.beans.factory.support;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -30,6 +30,8 @@ import org.springframework.lang.Nullable;
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Stephane Nicoll
* @author Sam Brannen
* @since 21.01.2004
* @param <E> the element type
*/
@@ -54,16 +56,16 @@ public class ManagedSet<E> extends LinkedHashSet<E> implements Mergeable, BeanMe
/**
* Return a new instance containing an arbitrary number of elements.
* Create a new instance containing an arbitrary number of elements.
* @param elements the elements to be contained in the set
* @param <E> the {@code Set}'s element type
* @return a {@code Set} containing the specified elements
* @return a {@code ManagedSet} containing the specified elements
* @since 5.3.16
*/
@SuppressWarnings("unchecked")
@SafeVarargs
public static <E> ManagedSet<E> of(E... elements) {
ManagedSet<E> set = new ManagedSet<>();
set.addAll(Arrays.asList(elements));
Collections.addAll(set, elements);
return set;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 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.
@@ -43,6 +43,7 @@ import org.springframework.core.io.ContextResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.WritableResource;
import org.springframework.core.io.support.ResourceArrayPropertyEditor;
import org.springframework.core.io.support.ResourcePatternResolver;
@@ -102,6 +103,7 @@ public class ResourceEditorRegistrar implements PropertyEditorRegistrar {
ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
doRegisterEditor(registry, Resource.class, baseEditor);
doRegisterEditor(registry, ContextResource.class, baseEditor);
doRegisterEditor(registry, WritableResource.class, baseEditor);
doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
@@ -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.
@@ -39,7 +39,7 @@ inline fun <reified T : Any> ListableBeanFactory.getBeansOfType(includeNonSingle
/**
* Extension for [ListableBeanFactory.getBeanNamesForAnnotation] providing a
* `getBeansOfType<Foo>()` variant.
* `getBeanNamesForAnnotation<Foo>()` variant.
*
* @author Sebastien Deleuze
* @since 5.0
@@ -25,6 +25,7 @@ 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;
@@ -153,7 +154,7 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
}
@Test
void propertyDescriptors() {
void propertyDescriptors() throws Exception {
TestBean target = new TestBean();
target.setSpouse(new TestBean());
BeanWrapper accessor = createAccessor(target);
@@ -182,11 +183,29 @@ class BeanWrapperTests extends AbstractPropertyAccessorTests {
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
@@ -26,7 +26,6 @@ import java.security.Principal;
import java.security.PrivilegedAction;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@@ -95,6 +94,7 @@ 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.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -178,10 +178,8 @@ class DefaultListableBeanFactoryTests {
registerBeanDefinitions(p);
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertBeanNamesForType(TestBean.class, false, false);
assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty();
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -212,10 +210,8 @@ class DefaultListableBeanFactoryTests {
registerBeanDefinitions(p);
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertBeanNamesForType(TestBean.class, false, false);
assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty();
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -245,10 +241,8 @@ class DefaultListableBeanFactoryTests {
registerBeanDefinitions(p);
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(0);
beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
assertThat(beanNames).hasSize(0);
assertBeanNamesForType(TestBean.class, false, false);
assertThat(lbf.getBeanNamesForAnnotation(SuppressWarnings.class)).isEmpty();
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
@@ -278,10 +272,8 @@ class DefaultListableBeanFactoryTests {
registerBeanDefinitions(p);
lbf.preInstantiateSingletons();
assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue();
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertThat(DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isFalse();
assertBeanNamesForType(TestBean.class, true, false, "x1");
assertThat(lbf.containsSingleton("x1")).isTrue();
assertThat(lbf.containsBean("x1")).isTrue();
assertThat(lbf.containsBean("&x1")).isTrue();
@@ -316,14 +308,10 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("&x2", Object.class)).isTrue();
assertThat(lbf.getType("x2")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x2")).isEqualTo(DummyFactory.class);
assertThat(lbf.getAliases("x1").length).isEqualTo(1);
assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2");
assertThat(lbf.getAliases("&x1").length).isEqualTo(1);
assertThat(lbf.getAliases("&x1")[0]).isEqualTo("&x2");
assertThat(lbf.getAliases("x2").length).isEqualTo(1);
assertThat(lbf.getAliases("x2")[0]).isEqualTo("x1");
assertThat(lbf.getAliases("&x2").length).isEqualTo(1);
assertThat(lbf.getAliases("&x2")[0]).isEqualTo("&x1");
assertThat(lbf.getAliases("x1")).containsExactly("x2");
assertThat(lbf.getAliases("&x1")).containsExactly("&x2");
assertThat(lbf.getAliases("x2")).containsExactly("x1");
assertThat(lbf.getAliases("&x2")).containsExactly("&x1");
}
@Test
@@ -333,9 +321,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("x1", rbd);
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertBeanNamesForType(TestBean.class, true, false, "x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
assertThat(lbf.containsBean("&x1")).isFalse();
@@ -358,9 +344,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("x1", rbd);
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertBeanNamesForType(TestBean.class, true, false, "x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
assertThat(lbf.containsBean("&x1")).isFalse();
@@ -385,9 +369,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("x1", rbd);
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertBeanNamesForType(TestBean.class, true, false, "x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
assertThat(lbf.containsBean("&x1")).isFalse();
@@ -413,9 +395,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("x1", rbd);
TestBeanFactory.initialized = false;
String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("x1");
assertBeanNamesForType(TestBean.class, true, false, "x1");
assertThat(lbf.containsSingleton("x1")).isFalse();
assertThat(lbf.containsBean("x1")).isTrue();
assertThat(lbf.containsBean("&x1")).isFalse();
@@ -448,14 +428,10 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.isTypeMatch("&x2", Object.class)).isFalse();
assertThat(lbf.getType("x2")).isEqualTo(TestBean.class);
assertThat(lbf.getType("&x2")).isNull();
assertThat(lbf.getAliases("x1").length).isEqualTo(1);
assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2");
assertThat(lbf.getAliases("&x1").length).isEqualTo(1);
assertThat(lbf.getAliases("&x1")[0]).isEqualTo("&x2");
assertThat(lbf.getAliases("x2").length).isEqualTo(1);
assertThat(lbf.getAliases("x2")[0]).isEqualTo("x1");
assertThat(lbf.getAliases("&x2").length).isEqualTo(1);
assertThat(lbf.getAliases("&x2")[0]).isEqualTo("&x1");
assertThat(lbf.getAliases("x1")).containsExactly("x2");
assertThat(lbf.getAliases("&x1")).containsExactly("&x2");
assertThat(lbf.getAliases("x2")).containsExactly("x1");
assertThat(lbf.getAliases("&x2")).containsExactly("&x1");
}
@Test
@@ -619,8 +595,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerSingleton("string", "A");
TestBean self = (TestBean) lbf.getBean("self");
assertThat(self.getStringArray()).hasSize(1);
assertThat(self.getStringArray()).contains("A");
assertThat(self.getStringArray()).containsExactly("A");
}
@Test
@@ -633,8 +608,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerSingleton("string", "A");
TestBean self = (TestBean) lbf.getBean("self");
assertThat(self.getStringArray()).hasSize(1);
assertThat(self.getStringArray()).contains("A");
assertThat(self.getStringArray()).containsExactly("A");
}
@Test
@@ -666,8 +640,7 @@ class DefaultListableBeanFactoryTests {
.withCauseInstanceOf(NotWritablePropertyException.class)
.satisfies(ex -> {
NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause();
assertThat(cause.getPossibleMatches()).hasSize(1);
assertThat(cause.getPossibleMatches()[0]).isEqualTo("age");
assertThat(cause.getPossibleMatches()).containsExactly("age");
});
}
@@ -685,7 +658,7 @@ class DefaultListableBeanFactoryTests {
lbf = new DefaultListableBeanFactory();
p = new Properties();
p.setProperty("kerry.(class)", TestBean.class.getName());
p.setProperty("kerry.(scope)", "prototype");
p.setProperty("kerry.(scope)", BeanDefinition.SCOPE_PROTOTYPE);
p.setProperty("kerry.age", "35");
registerBeanDefinitions(p);
kerry1 = (TestBean) lbf.getBean("kerry");
@@ -1145,7 +1118,7 @@ class DefaultListableBeanFactoryTests {
assertThat(lbf.containsBean("singletonObject")).isTrue();
assertThat(lbf.isSingleton("singletonObject")).isTrue();
assertThat(lbf.getType("singletonObject")).isEqualTo(TestBean.class);
assertThat(lbf.getAliases("singletonObject").length).isEqualTo(0);
assertThat(lbf.getAliases("singletonObject")).isEmpty();
DependenciesBean test = (DependenciesBean) lbf.getBean("test");
assertThat(lbf.getBean("singletonObject")).isEqualTo(singletonObject);
assertThat(test.getSpouse()).isEqualTo(singletonObject);
@@ -1791,12 +1764,12 @@ class DefaultListableBeanFactoryTests {
assertThat(bean.beanName).isEqualTo("bd1");
assertThat(bean.spouseAge).isEqualTo(42);
assertThat(lbf.getBeanNamesForType(ConstructorDependency.class).length).isEqualTo(1);
assertThat(lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length).isEqualTo(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)).length).isEqualTo(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)).length).isEqualTo(0);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class), true, true).length).isEqualTo(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class), true, true).length).isEqualTo(0);
assertThat(lbf.getBeanNamesForType(ConstructorDependency.class)).hasSize(1);
assertThat(lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class)).hasSize(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class))).hasSize(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class))).isEmpty();
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class), true, true)).hasSize(1);
assertThat(lbf.getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class), true, true)).isEmpty();
}
private RootBeanDefinition createConstructorDependencyBeanDefinition(int age) {
@@ -1861,46 +1834,45 @@ class DefaultListableBeanFactoryTests {
@Test
void getBeanNamesForTypeBeforeFactoryBeanCreation() {
FactoryBeanThatShouldntBeCalled.instantiated = false;
lbf.registerBeanDefinition("factoryBean", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class));
assertThat(lbf.containsSingleton("factoryBean")).isFalse();
assertThat(FactoryBeanThatShouldntBeCalled.instantiated).isFalse();
String[] beanNames = lbf.getBeanNamesForType(Runnable.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = lbf.getBeanNamesForType(Callable.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = lbf.getBeanNamesForType(RepositoryFactoryInformation.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = lbf.getBeanNamesForType(FactoryBean.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
assertBeanNamesForType(Runnable.class, false, false, "&factoryBean");
assertBeanNamesForType(Callable.class, false, false, "&factoryBean");
assertBeanNamesForType(RepositoryFactoryInformation.class, false, false, "&factoryBean");
assertBeanNamesForType(FactoryBean.class, false, false, "&factoryBean");
}
@Test
void getBeanNamesForTypeAfterFactoryBeanCreation() {
FactoryBeanThatShouldntBeCalled.instantiated = false;
lbf.registerBeanDefinition("factoryBean", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class));
lbf.getBean("&factoryBean");
assertThat(FactoryBeanThatShouldntBeCalled.instantiated).isTrue();
assertThat(lbf.containsSingleton("factoryBean")).isTrue();
String[] beanNames = lbf.getBeanNamesForType(Runnable.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
assertBeanNamesForType(Runnable.class, false, false, "&factoryBean");
assertBeanNamesForType(Callable.class, false, false, "&factoryBean");
assertBeanNamesForType(RepositoryFactoryInformation.class, false, false, "&factoryBean");
assertBeanNamesForType(FactoryBean.class, false, false, "&factoryBean");
}
beanNames = lbf.getBeanNamesForType(Callable.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
@Test // gh-28616
void getBeanNamesForTypeWithPrototypeScopedFactoryBean() {
FactoryBeanThatShouldntBeCalled.instantiated = false;
RootBeanDefinition beanDefinition = new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class);
beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
lbf.registerBeanDefinition("factoryBean", beanDefinition);
assertThat(FactoryBeanThatShouldntBeCalled.instantiated).isFalse();
assertThat(lbf.containsSingleton("factoryBean")).isFalse();
beanNames = lbf.getBeanNamesForType(RepositoryFactoryInformation.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = lbf.getBeanNamesForType(FactoryBean.class, false, false);
assertThat(beanNames.length).isEqualTo(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
// We should not find any beans of the following types if the FactoryBean itself is prototype-scoped.
assertBeanNamesForType(Runnable.class, false, false);
assertBeanNamesForType(Callable.class, false, false);
assertBeanNamesForType(RepositoryFactoryInformation.class, false, false);
assertBeanNamesForType(FactoryBean.class, false, false);
}
/**
@@ -2165,8 +2137,7 @@ class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(lbf::preInstantiateSingletons);
}
@Test
@@ -2174,8 +2145,7 @@ class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(lbf::preInstantiateSingletons);
}
@Test
@@ -2183,8 +2153,7 @@ class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
lbf.registerBeanDefinition("test", bd);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() ->
lbf.getBeansOfType(String.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(() -> lbf.getBeansOfType(String.class));
}
@Test
@@ -2211,8 +2180,7 @@ class DefaultListableBeanFactoryTests {
RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyWithClassResolution.class);
bd.getConstructorArgumentValues().addGenericArgumentValue("java.lang.Strin");
lbf.registerBeanDefinition("test", bd);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(
lbf::preInstantiateSingletons);
assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(lbf::preInstantiateSingletons);
}
@Test
@@ -2236,7 +2204,13 @@ class DefaultListableBeanFactoryTests {
@Test
void prototypeFactoryBeanNotEagerlyCalled() {
lbf.registerBeanDefinition("test", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class));
lbf.preInstantiateSingletons();
assertThatNoException().isThrownBy(lbf::preInstantiateSingletons);
}
@Test
void prototypeFactoryBeanNotEagerlyCalledInCaseOfBeanClassName() {
lbf.registerBeanDefinition("test", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class.getName(), null, null));
assertThatNoException().isThrownBy(lbf::preInstantiateSingletons);
}
@Test
@@ -2276,13 +2250,6 @@ class DefaultListableBeanFactoryTests {
assertThat(factory.initialized).isTrue();
}
@Test
void prototypeFactoryBeanNotEagerlyCalledInCaseOfBeanClassName() {
lbf.registerBeanDefinition("test",
new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class.getName(), null, null));
lbf.preInstantiateSingletons();
}
@Test
void prototypeStringCreatedRepeatedly() {
RootBeanDefinition stringDef = new RootBeanDefinition(String.class);
@@ -2462,10 +2429,7 @@ class DefaultListableBeanFactoryTests {
lbf.registerBeanDefinition("fmWithArgs", factoryMethodDefinitionWithArgs);
assertThat(lbf.getBeanDefinitionCount()).isEqualTo(4);
List<String> tbNames = Arrays.asList(lbf.getBeanNamesForType(TestBean.class));
assertThat(tbNames.contains("fmWithProperties")).isTrue();
assertThat(tbNames.contains("fmWithArgs")).isTrue();
assertThat(tbNames.size()).isEqualTo(2);
assertBeanNamesForType(TestBean.class, true, true, "fmWithProperties", "fmWithArgs");
TestBean tb = (TestBean) lbf.getBean("fmWithProperties");
TestBean second = (TestBean) lbf.getBean("fmWithProperties");
@@ -2669,6 +2633,19 @@ class DefaultListableBeanFactoryTests {
return (new org.springframework.beans.factory.support.PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p, prefix);
}
private void assertBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit, String... names) {
if (names.length == 0) {
assertThat(lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit))
.as("bean names for type " + type.getName())
.isEmpty();
}
else {
assertThat(lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit))
.as("bean names for type " + type.getName())
.containsExactly(names);
}
}
public static class NoDependencies {
@@ -2859,6 +2836,12 @@ class DefaultListableBeanFactoryTests {
public static class FactoryBeanThatShouldntBeCalled<T extends Repository<S, ID>, S, ID extends Serializable>
extends RepositoryFactoryBeanSupport<T, S, ID> implements Runnable, Callable<T> {
static boolean instantiated = false;
{
instantiated = true;
}
@Override
public T getObject() {
throw new IllegalStateException();
@@ -25,61 +25,61 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Unit tests for {@link ManagedList}.
*
* @author Rick Evans
* @author Juergen Hoeller
* @author Sam Brannen
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ManagedListTests {
class ManagedListTests {
@Test
public void mergeSunnyDay() {
void mergeSunnyDay() {
ManagedList parent = ManagedList.of("one", "two");
ManagedList child = ManagedList.of("three");
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3);
assertThat(mergedList).as("merge() obviously did not work.").containsExactly("one", "two", "three");
}
@Test
public void mergeWithNullParent() {
void mergeWithNullParent() {
ManagedList child = ManagedList.of("one");
child.setMergeEnabled(true);
assertThat(child.merge(null)).isSameAs(child);
}
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
void mergeNotAllowedWhenMergeNotEnabled() {
ManagedList child = new ManagedList();
assertThatIllegalStateException().isThrownBy(() ->
child.merge(null));
assertThatIllegalStateException().isThrownBy(() -> child.merge(null));
}
@Test
public void mergeWithNonCompatibleParentType() {
void mergeWithIncompatibleParentType() {
ManagedList child = ManagedList.of("one");
child.setMergeEnabled(true);
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
assertThatIllegalArgumentException().isThrownBy(() -> child.merge("hello"));
}
@Test
public void mergeEmptyChild() {
void mergeEmptyChild() {
ManagedList parent = ManagedList.of("one", "two");
ManagedList child = new ManagedList();
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(2);
assertThat(mergedList).as("merge() obviously did not work.").containsExactly("one", "two");
}
@Test
public void mergeChildValuesOverrideTheParents() {
void mergedChildValuesDoNotOverrideTheParents() {
// doesn't make much sense in the context of a list...
ManagedList parent = ManagedList.of("one", "two");
ManagedList child = ManagedList.of("one");
child.setMergeEnabled(true);
List mergedList = child.merge(parent);
assertThat(mergedList.size()).as("merge() obviously did not work.").isEqualTo(3);
assertThat(mergedList).as("merge() obviously did not work.").containsExactly("one", "two", "one");
}
}
@@ -25,61 +25,62 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Unit tests for {@link ManagedSet}.
*
* @author Rick Evans
* @author Juergen Hoeller
* @author Sam Brannen
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ManagedSetTests {
class ManagedSetTests {
@Test
public void mergeSunnyDay() {
void mergeSunnyDay() {
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet child = ManagedSet.of("three");
child.add("three");
child.add("four");
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(3);
assertThat(mergedSet).as("merge() obviously did not work.").containsExactly("one", "two", "three", "four");
}
@Test
public void mergeWithNullParent() {
void mergeWithNullParent() {
ManagedSet child = ManagedSet.of("one");
child.setMergeEnabled(true);
assertThat(child.merge(null)).isSameAs(child);
}
@Test
public void mergeNotAllowedWhenMergeNotEnabled() {
assertThatIllegalStateException().isThrownBy(() ->
new ManagedSet().merge(null));
void mergeNotAllowedWhenMergeNotEnabled() {
assertThatIllegalStateException().isThrownBy(() -> new ManagedSet().merge(null));
}
@Test
public void mergeWithNonCompatibleParentType() {
void mergeWithNonCompatibleParentType() {
ManagedSet child = ManagedSet.of("one");
child.setMergeEnabled(true);
assertThatIllegalArgumentException().isThrownBy(() ->
child.merge("hello"));
assertThatIllegalArgumentException().isThrownBy(() -> child.merge("hello"));
}
@Test
public void mergeEmptyChild() {
void mergeEmptyChild() {
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet child = new ManagedSet();
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(2);
assertThat(mergedSet).as("merge() obviously did not work.").containsExactly("one", "two");
}
@Test
public void mergeChildValuesOverrideTheParents() {
void mergeChildValuesOverrideTheParents() {
// asserts that the set contract is not violated during a merge() operation...
ManagedSet parent = ManagedSet.of("one", "two");
ManagedSet child = ManagedSet.of("one");
child.setMergeEnabled(true);
Set mergedSet = child.merge(parent);
assertThat(mergedSet.size()).as("merge() obviously did not work.").isEqualTo(2);
assertThat(mergedSet).as("merge() obviously did not work.").containsExactly("one", "two");
}
}
@@ -58,6 +58,7 @@ import org.springframework.core.io.Resource;
import org.springframework.core.testfixture.security.TestPrincipal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
@@ -303,14 +304,14 @@ public class CallbacksSecurityTests {
Method method = bean.getClass().getMethod("destroy");
method.setAccessible(true);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
assertThatException().isThrownBy(() ->
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
method.invoke(bean);
return null;
}, acc));
Class<ConstructorBean> cl = ConstructorBean.class;
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
assertThatException().isThrownBy(() ->
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
cl.newInstance(), acc));
}
@@ -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,8 +23,7 @@ import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.io.ClassPathResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatException;
/**
* With Spring 3.1, bean id attributes (and all other id attributes across the
@@ -40,22 +39,23 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#withDuplicateName
* @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#withDuplicateNameInAlias
*/
public class DuplicateBeanIdTests {
class DuplicateBeanIdTests {
@Test
public void duplicateBeanIdsWithinSameNestingLevelRaisesError() {
void duplicateBeanIdsWithinSameNestingLevelRaisesError() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
assertThatExceptionOfType(Exception.class).as("duplicate ids in same nesting level").isThrownBy(() ->
assertThatException().as("duplicate ids in same nesting level").isThrownBy(() ->
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-sameLevel-context.xml", this.getClass())));
}
@Test
public void duplicateBeanIdsAcrossNestingLevels() {
void duplicateBeanIdsAcrossNestingLevels() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
reader.loadBeanDefinitions(new ClassPathResource("DuplicateBeanIdTests-multiLevel-context.xml", this.getClass()));
TestBean testBean = bf.getBean(TestBean.class); // there should be only one
assertThat(testBean.getName()).isEqualTo("nested");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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,6 +22,7 @@ import javax.lang.model.element.Element;
/**
* Provide the list of stereotypes that match an {@link Element}.
*
* <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.
*
@@ -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.
@@ -40,7 +40,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.contextsupport.testfixture.jcache.JCacheableService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Stephane Nicoll
@@ -86,8 +86,8 @@ public class JCacheCustomInterceptorTests {
@Test
public void customInterceptorAppliesWithCheckedException() {
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
cs.cacheWithCheckedException("id", true))
assertThatRuntimeException()
.isThrownBy(() -> cs.cacheWithCheckedException("id", true))
.withCauseExactlyInstanceOf(IOException.class);
}
@@ -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.
@@ -37,9 +37,9 @@ public class SimpleLocaleContext implements LocaleContext {
/**
* Create a new SimpleLocaleContext that exposes the specified Locale.
* Every {@link #getLocale()} call will return this Locale.
* @param locale the Locale to expose, or {@code null} for no specific one
* Create a new {@code SimpleLocaleContext} that exposes the specified {@link Locale}.
* <p>Every {@link #getLocale()} call will return this locale.
* @param locale the {@code Locale} to expose, or {@code null} for no specific one
*/
public SimpleLocaleContext(@Nullable Locale locale) {
this.locale = locale;
@@ -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.
@@ -143,7 +143,7 @@ public class NotificationListenerRegistrar extends NotificationListenerHolder
this.actualObjectNames = getResolvedObjectNames();
if (this.actualObjectNames != null) {
if (logger.isDebugEnabled()) {
logger.debug("Registering NotificationListener for MBeans " + Arrays.asList(this.actualObjectNames));
logger.debug("Registering NotificationListener for MBeans " + Arrays.toString(this.actualObjectNames));
}
for (ObjectName actualObjectName : this.actualObjectNames) {
this.server.addNotificationListener(
@@ -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.
@@ -762,7 +762,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
* <p>The default implementation delegates to {@link JmxUtils#isMBean},
* which checks for {@link javax.management.DynamicMBean} classes as well
* as classes with corresponding "*MBean" interface (Standard MBeans)
* or corresponding "*MXBean" interface (Java 6 MXBeans).
* or corresponding "*MXBean" interface (Java MXBeans).
* @param beanClass the bean class to analyze
* @return whether the class qualifies as an MBean
* @see org.springframework.jmx.support.JmxUtils#isMBean(Class)
@@ -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.
@@ -255,7 +255,7 @@ public abstract class JmxUtils {
* Determine whether the given bean class qualifies as an MBean as-is.
* <p>This implementation checks for {@link javax.management.DynamicMBean}
* classes as well as classes with corresponding "*MBean" interface
* (Standard MBeans) or corresponding "*MXBean" interface (Java 6 MXBeans).
* (Standard MBeans) or corresponding "*MXBean" interface (Java MXBeans).
* @param clazz the bean class to analyze
* @return whether the class qualifies as an MBean
* @see org.springframework.jmx.export.MBeanExporter#isMBean(Class)
@@ -289,7 +289,7 @@ public abstract class JmxUtils {
}
/**
* Return the Java 6 MXBean interface exists for the given class, if any
* Return the Java MXBean interface for the given class, if any
* (that is, an interface whose name ends with "MXBean" and/or
* carries an appropriate MXBean annotation).
* @param clazz the class to check
@@ -72,6 +72,8 @@ import org.springframework.util.concurrent.ListenableFutureTask;
* {@link org.springframework.scheduling.concurrent.ConcurrentTaskExecutor} adapter.
*
* @author Juergen Hoeller
* @author Rémy Guihard
* @author Sam Brannen
* @since 2.0
* @see org.springframework.core.task.TaskExecutor
* @see java.util.concurrent.ThreadPoolExecutor
@@ -155,7 +157,7 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
/**
* Set the ThreadPoolExecutor's keep-alive seconds.
* Default is 60.
* <p>Default is 60.
* <p><b>This setting can be modified at runtime, for example through JMX.</b>
*/
public void setKeepAliveSeconds(int keepAliveSeconds) {
@@ -178,7 +180,7 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
/**
* Set the capacity for the ThreadPoolExecutor's BlockingQueue.
* Default is {@code Integer.MAX_VALUE}.
* <p>Default is {@code Integer.MAX_VALUE}.
* <p>Any positive value will lead to a LinkedBlockingQueue instance;
* any other value will lead to a SynchronousQueue instance.
* @see java.util.concurrent.LinkedBlockingQueue
@@ -188,6 +190,15 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
this.queueCapacity = queueCapacity;
}
/**
* Return the capacity for the ThreadPoolExecutor's BlockingQueue.
* @since 5.3.21
* @see #setQueueCapacity(int)
*/
public int getQueueCapacity() {
return this.queueCapacity;
}
/**
* Specify whether to allow core threads to time out. This enables dynamic
* growing and shrinking even in combination with a non-zero queue (since
@@ -316,6 +327,19 @@ public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport
return this.threadPoolExecutor.getPoolSize();
}
/**
* Return the current queue size.
* @since 5.3.21
* @see java.util.concurrent.ThreadPoolExecutor#getQueue()
*/
public int getQueueSize() {
if (this.threadPoolExecutor == null) {
// Not initialized yet: assume no queued tasks.
return 0;
}
return this.threadPoolExecutor.getQueue().size();
}
/**
* Return the number of currently active threads.
* @see java.util.concurrent.ThreadPoolExecutor#getActiveCount()
@@ -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.
@@ -36,7 +36,7 @@ import org.springframework.util.StringUtils;
/**
* {@link org.springframework.scripting.ScriptFactory} implementation based
* on the JSR-223 script engine abstraction (as included in Java 6+).
* on the JSR-223 script engine abstraction (as included in Java).
* Supports JavaScript, Groovy, JRuby, and other JSR-223 compliant engines.
*
* <p>Typically used in combination with a
@@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Adrian Colyer
@@ -35,12 +35,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
class SPR3064Tests {
@Test
void testServiceIsAdvised() {
void serviceIsAdvised() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
Service service = ctx.getBean(Service.class);
assertThatExceptionOfType(RuntimeException.class)
assertThatRuntimeException()
.isThrownBy(service::serveMe)
.withMessage("advice invoked");
@@ -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.
@@ -74,9 +74,11 @@ import org.springframework.core.testfixture.io.SerializationTestUtils;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Rod Johnson
@@ -431,7 +433,7 @@ public abstract class AbstractAopProxyTests {
pc.setTargetSource(mockTargetSource);
AopProxy aop = createAopProxy(pc);
assertThatExceptionOfType(Exception.class).isThrownBy(() -> {
assertThatException().isThrownBy(() -> {
ITestBean tb = (ITestBean) aop.getProxy();
// Note: exception param below isn't used
tb.exceptional(expectedException);
@@ -459,8 +461,7 @@ public abstract class AbstractAopProxyTests {
AopProxy aop = createAopProxy(pc);
ITestBean tb = (ITestBean) aop.getProxy();
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(
tb::getAge)
assertThatExceptionOfType(UndeclaredThrowableException.class).isThrownBy(tb::getAge)
.satisfies(ex -> assertThat(ex.getUndeclaredThrowable()).isEqualTo(unexpectedException));
}
@@ -480,8 +481,8 @@ public abstract class AbstractAopProxyTests {
AopProxy aop = createAopProxy(pc);
ITestBean tb = (ITestBean) aop.getProxy();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
tb::getAge)
assertThatRuntimeException()
.isThrownBy(tb::getAge)
.matches(unexpectedException::equals);
}
@@ -571,8 +572,7 @@ public abstract class AbstractAopProxyTests {
lockable.lock();
assertThat(itb.getAge()).isEqualTo(newAge);
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
itb.setAge(1));
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> itb.setAge(1));
assertThat(itb.getAge()).isEqualTo(newAge);
// Unlock
@@ -675,7 +675,7 @@ public abstract class AbstractAopProxyTests {
target.setAge(21);
ProxyFactory pc = new ProxyFactory(target);
pc.addAdvisor(new DefaultIntroductionAdvisor(new DummyIntroductionAdviceImpl(), Comparable.class));
assertThatExceptionOfType(Exception.class).isThrownBy(() -> {
assertThatException().isThrownBy(() -> {
// TODO May fail on either call: may want to tighten up definition
ITestBean proxied = (ITestBean) createProxy(pc);
proxied.getName();
@@ -725,8 +725,7 @@ public abstract class AbstractAopProxyTests {
pc.addAdvisor(new DefaultIntroductionAdvisor(new MyDi()));
TimeStamped ts = (TimeStamped) createProxy(pc);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(
ts::getTimeStamp);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(ts::getTimeStamp);
}
/**
@@ -754,8 +753,8 @@ public abstract class AbstractAopProxyTests {
pc.addAdvice(new NopInterceptor());
ITestBean proxied = (ITestBean) createProxy(pc);
pc.setFrozen(true);
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add interceptor when frozen").isThrownBy(() ->
pc.addAdvice(0, new NopInterceptor()))
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add interceptor when frozen")
.isThrownBy(() -> pc.addAdvice(0, new NopInterceptor()))
.withMessageContaining("frozen");
// Check it still works: proxy factory state shouldn't have been corrupted
assertThat(proxied.getAge()).isEqualTo(target.getAge());
@@ -777,8 +776,8 @@ public abstract class AbstractAopProxyTests {
Advised advised = (Advised) proxied;
assertThat(pc.isFrozen()).isTrue();
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen").isThrownBy(() ->
advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())))
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to add Advisor when frozen")
.isThrownBy(() -> advised.addAdvisor(new DefaultPointcutAdvisor(new NopInterceptor())))
.withMessageContaining("frozen");
// Check it still works: proxy factory state shouldn't have been corrupted
assertThat(proxied.getAge()).isEqualTo(target.getAge());
@@ -797,8 +796,8 @@ public abstract class AbstractAopProxyTests {
Advised advised = (Advised) proxied;
assertThat(pc.isFrozen()).isTrue();
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen").isThrownBy(() ->
advised.removeAdvisor(0))
assertThatExceptionOfType(AopConfigException.class).as("Shouldn't be able to remove Advisor when frozen")
.isThrownBy(() -> advised.removeAdvisor(0))
.withMessageContaining("frozen");
// Didn't get removed
assertThat(advised.getAdvisors().length).isEqualTo(1);
@@ -1311,8 +1310,8 @@ public abstract class AbstractAopProxyTests {
assertThat(cca.getCalls()).isEqualTo(2);
assertThat(proxied.getAge()).isEqualTo(26);
assertThat(cca.getCalls()).isEqualTo(4);
assertThatExceptionOfType(SpecializedUncheckedException.class).as("Should have thrown CannotGetJdbcConnectionException").isThrownBy(() ->
proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null)));
assertThatExceptionOfType(SpecializedUncheckedException.class).as("Should have thrown CannotGetJdbcConnectionException")
.isThrownBy(() -> proxied.exceptional(new SpecializedUncheckedException("foo", (SQLException)null)));
assertThat(cca.getCalls()).isEqualTo(6);
}
@@ -1346,8 +1345,8 @@ public abstract class AbstractAopProxyTests {
assertThat(nop1.getCount()).isEqualTo(1);
assertThat(nop2.getCount()).isEqualTo(1);
// Will fail, after invoking Nop1
assertThatExceptionOfType(RuntimeException.class).as("before advice should have ended chain").isThrownBy(() ->
proxied.setAge(26))
assertThatRuntimeException().as("before advice should have ended chain")
.isThrownBy(() -> proxied.setAge(26))
.matches(rex::equals);
assertThat(ba.getCalls()).isEqualTo(2);
assertThat(nop1.getCount()).isEqualTo(2);
@@ -1411,8 +1410,7 @@ public abstract class AbstractAopProxyTests {
assertThat(car.getCalls()).isEqualTo(2);
Exception exc = new Exception();
// On exception it won't be invoked
assertThatExceptionOfType(Throwable.class).isThrownBy(() ->
proxied.exceptional(exc))
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> proxied.exceptional(exc))
.satisfies(ex -> assertThat(ex).isSameAs(exc));
assertThat(car.getCalls()).isEqualTo(2);
}
@@ -1442,12 +1440,11 @@ public abstract class AbstractAopProxyTests {
assertThat(th.getCalls()).isEqualTo(0);
Exception ex = new Exception();
// Will be advised but doesn't match
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
proxied.echoException(1, ex))
assertThatException().isThrownBy(() -> proxied.echoException(1, ex))
.matches(ex::equals);
FileNotFoundException fex = new FileNotFoundException();
assertThatExceptionOfType(FileNotFoundException.class).isThrownBy(() ->
proxied.echoException(1, fex))
assertThatExceptionOfType(FileNotFoundException.class)
.isThrownBy(() -> proxied.echoException(1, fex))
.matches(fex::equals);
assertThat(th.getCalls("ioException")).isEqualTo(1);
}
@@ -1468,14 +1465,12 @@ public abstract class AbstractAopProxyTests {
assertThat(th.getCalls()).isEqualTo(0);
Exception ex = new Exception();
// Will be advised but doesn't match
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
proxied.echoException(1, ex))
assertThatException().isThrownBy(() -> proxied.echoException(1, ex))
.matches(ex::equals);
// Subclass of RemoteException
MarshalException mex = new MarshalException("");
assertThatExceptionOfType(MarshalException.class).isThrownBy(() ->
proxied.echoException(1, mex))
assertThatExceptionOfType(MarshalException.class).isThrownBy(() -> proxied.echoException(1, mex))
.matches(mex::equals);
assertThat(th.getCalls("remoteException")).isEqualTo(1);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -61,6 +61,7 @@ import org.springframework.core.testfixture.io.SerializationTestUtils;
import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIOException;
@@ -310,7 +311,7 @@ public class ProxyFactoryBeanTests {
assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2);
ITestBean tb1 = (ITestBean) factory.getBean("test1");
assertThatExceptionOfType(Exception.class)
assertThatException()
.isThrownBy(tb1::toString)
.isSameAs(ex);
}
@@ -438,8 +439,7 @@ public class ProxyFactoryBeanTests {
assertThat(cba.getCalls()).isEqualTo(2);
assertThat(th.getCalls()).isEqualTo(0);
Exception expected = new Exception();
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
echo.echoException(1, expected))
assertThatException().isThrownBy(() -> echo.echoException(1, expected))
.matches(expected::equals);
// No throws handler method: count should still be 0
assertThat(th.getCalls()).isEqualTo(0);
@@ -586,8 +586,7 @@ public class ProxyFactoryBeanTests {
((Lockable) bean1).lock();
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
bean1.setAge(5));
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> bean1.setAge(5));
bean2.setAge(6); //do not expect LockedException"
}
@@ -607,8 +606,7 @@ public class ProxyFactoryBeanTests {
((Lockable) bean1).lock();
assertThatExceptionOfType(LockedException.class).isThrownBy(() ->
bean1.setAge(5));
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> bean1.setAge(5));
// do not expect LockedException
bean2.setAge(6);
@@ -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.
@@ -37,7 +37,7 @@ import org.springframework.context.testfixture.cache.beans.CacheableService;
import org.springframework.context.testfixture.cache.beans.DefaultCacheableService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Stephane Nicoll
@@ -76,8 +76,8 @@ public class CustomInterceptorTests {
@Test
public void customInterceptorAppliesWithCheckedException() {
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
this.cs.throwChecked(0L))
assertThatRuntimeException()
.isThrownBy(() -> this.cs.throwChecked(0L))
.withCauseExactlyInstanceOf(IOException.class);
}
@@ -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.
@@ -148,25 +148,53 @@ class AnnotationConfigApplicationContextTests {
void nullReturningBeanPostProcessor() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AutowiredConfig.class);
// 1st BPP always gets invoked
context.getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof TestBean) {
TestBean testBean = (TestBean) bean;
testBean.name = testBean.name + "-before";
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof TestBean) {
TestBean testBean = (TestBean) bean;
testBean.name = testBean.name + "-after";
}
return bean;
}
});
// 2nd BPP always returns null for a TestBean
context.getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return (bean instanceof TestBean ? null : bean);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return (bean instanceof TestBean ? null : bean);
}
});
// 3rd BPP never gets invoked with a TestBean
context.getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
bean.getClass().getName();
assertThat(bean).isNotInstanceOf(TestBean.class);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
bean.getClass().getName();
assertThat(bean).isNotInstanceOf(TestBean.class);
return bean;
}
});
context.refresh();
TestBean testBean = context.getBean(TestBean.class);
assertThat(testBean).isNotNull();
assertThat(testBean.name).isEqualTo("foo-before-after");
}
@Test
@@ -52,7 +52,7 @@ import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@@ -161,8 +161,8 @@ public class ApplicationContextEventTests extends AbstractApplicationEventListen
RuntimeException thrown = new RuntimeException();
willThrow(thrown).given(listener).onApplicationEvent(evt);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
smc.multicastEvent(evt))
assertThatRuntimeException()
.isThrownBy(() -> smc.multicastEvent(evt))
.satisfies(ex -> assertThat(ex).isSameAs(thrown));
}
@@ -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.
@@ -28,6 +28,7 @@ import org.springframework.aop.framework.ProxyFactory;
import org.springframework.jndi.JndiTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -132,7 +133,7 @@ public class LocalSlsbInvokerInterceptorTests {
pf.addAdvice(si);
LocalInterfaceWithBusinessMethods target = (LocalInterfaceWithBusinessMethods) pf.getProxy();
assertThatExceptionOfType(Exception.class)
assertThatException()
.isThrownBy(target::targetMethod)
.isSameAs(expected);
@@ -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.
@@ -32,6 +32,7 @@ import org.springframework.jndi.JndiTemplate;
import org.springframework.remoting.RemoteAccessException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -195,8 +196,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
assertThatExceptionOfType(RemoteException.class).isThrownBy(
target::targetMethod);
assertThatExceptionOfType(RemoteException.class).isThrownBy(target::targetMethod);
verify(mockContext).close();
verify(ejb, times(2)).remove();
@@ -245,8 +245,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
si.setCacheHome(cacheHome);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
assertThatExceptionOfType(ConnectException.class).isThrownBy(
target::targetMethod);
assertThatExceptionOfType(ConnectException.class).isThrownBy(target::targetMethod);
verify(mockContext, times(lookupCount)).close();
verify(ejb, times(2)).remove();
@@ -281,8 +280,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
BusinessInterface target = (BusinessInterface) configuredProxy(si, BusinessInterface.class);
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(
target::targetMethod);
assertThatExceptionOfType(RemoteAccessException.class).isThrownBy(target::targetMethod);
verify(mockContext).close();
verify(ejb).remove();
@@ -308,7 +306,7 @@ public class SimpleRemoteSlsbInvokerInterceptorTests {
SimpleRemoteSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
RemoteInterface target = (RemoteInterface) configuredProxy(si, RemoteInterface.class);
assertThatExceptionOfType(Exception.class)
assertThatException()
.isThrownBy(target::targetMethod)
.isSameAs(expected);
verify(mockContext).close();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -132,11 +132,11 @@ public class DateFormattingTests {
TypeMismatchException exception = fieldError.unwrap(TypeMismatchException.class);
assertThat(exception)
.hasMessageContaining("for property 'styleDate'")
.hasCauseInstanceOf(ConversionFailedException.class).getCause()
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value '99/01/01'")
.hasCauseInstanceOf(IllegalArgumentException.class).getCause()
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [99/01/01]")
.hasCauseInstanceOf(ParseException.class).getCause()
.hasCauseInstanceOf(ParseException.class).cause()
// Unable to parse date time value "99/01/01" using configuration from
// @org.springframework.format.annotation.DateTimeFormat(pattern=, style=S-, iso=NONE, fallbackPatterns=[])
// We do not check "fallbackPatterns=[]", since the array representation in the toString()
@@ -147,7 +147,7 @@ public class DateFormattingTests {
"Unable to parse date time value \"99/01/01\" using configuration from",
"@org.springframework.format.annotation.DateTimeFormat",
"style=", "S-", "iso=NONE")
.hasCauseInstanceOf(ParseException.class).getCause()
.hasCauseInstanceOf(ParseException.class).cause()
.hasMessageStartingWith("Unparseable date: \"99/01/01\"")
.hasNoCause();
}
@@ -352,11 +352,11 @@ public class DateFormattingTests {
FieldError fieldError = bindingResult.getFieldError(propertyName);
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'patternDateWithFallbackPatterns'")
.hasCauseInstanceOf(ConversionFailedException.class).getCause()
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value '210302'")
.hasCauseInstanceOf(IllegalArgumentException.class).getCause()
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [210302]")
.hasCauseInstanceOf(ParseException.class).getCause()
.hasCauseInstanceOf(ParseException.class).cause()
// Unable to parse date time value "210302" using configuration from
// @org.springframework.format.annotation.DateTimeFormat(
// pattern=yyyy-MM-dd, style=SS, iso=NONE, fallbackPatterns=[M/d/yy, yyyyMMdd, yyyy.MM.dd])
@@ -364,7 +364,7 @@ public class DateFormattingTests {
"Unable to parse date time value \"210302\" using configuration from",
"@org.springframework.format.annotation.DateTimeFormat",
"yyyy-MM-dd", "M/d/yy", "yyyyMMdd", "yyyy.MM.dd")
.hasCauseInstanceOf(ParseException.class).getCause()
.hasCauseInstanceOf(ParseException.class).cause()
.hasMessageStartingWith("Unparseable date: \"210302\"")
.hasNoCause();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -332,11 +332,11 @@ class DateTimeFormattingTests {
FieldError fieldError = bindingResult.getFieldError(propertyName);
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'isoLocalDate'")
.hasCauseInstanceOf(ConversionFailedException.class).getCause()
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value '2009-31-10'")
.hasCauseInstanceOf(IllegalArgumentException.class).getCause()
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [2009-31-10]")
.hasCauseInstanceOf(DateTimeParseException.class).getCause()
.hasCauseInstanceOf(DateTimeParseException.class).cause()
// Unable to parse date time value "2009-31-10" using configuration from
// @org.springframework.format.annotation.DateTimeFormat(pattern=, style=SS, iso=DATE, fallbackPatterns=[])
// We do not check "fallbackPatterns=[]", since the array representation in the toString()
@@ -344,9 +344,9 @@ class DateTimeFormattingTests {
.hasMessageContainingAll(
"Unable to parse date time value \"2009-31-10\" using configuration from",
"@org.springframework.format.annotation.DateTimeFormat", "iso=DATE")
.hasCauseInstanceOf(DateTimeParseException.class).getCause()
.hasCauseInstanceOf(DateTimeParseException.class).cause()
.hasMessageStartingWith("Text '2009-31-10'")
.hasCauseInstanceOf(DateTimeException.class).getCause()
.hasCauseInstanceOf(DateTimeException.class).cause()
.hasMessageContaining("Invalid value for MonthOfYear (valid values 1 - 12): 31")
.hasNoCause();
}
@@ -539,11 +539,11 @@ class DateTimeFormattingTests {
FieldError fieldError = bindingResult.getFieldError(propertyName);
assertThat(fieldError.unwrap(TypeMismatchException.class))
.hasMessageContaining("for property 'patternLocalDateWithFallbackPatterns'")
.hasCauseInstanceOf(ConversionFailedException.class).getCause()
.hasCauseInstanceOf(ConversionFailedException.class).cause()
.hasMessageContaining("for value '210302'")
.hasCauseInstanceOf(IllegalArgumentException.class).getCause()
.hasCauseInstanceOf(IllegalArgumentException.class).cause()
.hasMessageContaining("Parse attempt failed for value [210302]")
.hasCauseInstanceOf(DateTimeParseException.class).getCause()
.hasCauseInstanceOf(DateTimeParseException.class).cause()
// Unable to parse date time value "210302" using configuration from
// @org.springframework.format.annotation.DateTimeFormat(
// pattern=yyyy-MM-dd, style=SS, iso=NONE, fallbackPatterns=[M/d/yy, yyyyMMdd, yyyy.MM.dd])
@@ -551,7 +551,7 @@ class DateTimeFormattingTests {
"Unable to parse date time value \"210302\" using configuration from",
"@org.springframework.format.annotation.DateTimeFormat",
"yyyy-MM-dd", "M/d/yy", "yyyyMMdd", "yyyy.MM.dd")
.hasCauseInstanceOf(DateTimeParseException.class).getCause()
.hasCauseInstanceOf(DateTimeParseException.class).cause()
.hasMessageStartingWith("Text '210302'")
.hasNoCause();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -59,6 +59,7 @@ import org.springframework.jmx.support.RegistrationPolicy;
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.Assertions.assertThatRuntimeException;
/**
* Integration tests for the {@link MBeanExporter} class.
@@ -589,8 +590,8 @@ public class MBeanExporterTests extends AbstractMBeanServerTests {
exporter.setBeans(beansToExport);
exporter.setBeanFactory(factory);
assertThatExceptionOfType(RuntimeException.class).as("failed during creation of RuntimeExceptionThrowingConstructorBean").isThrownBy(() ->
start(exporter));
assertThatRuntimeException().as("failed during creation of RuntimeExceptionThrowingConstructorBean")
.isThrownBy(() -> start(exporter));
assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException",
ObjectNameManager.getInstance(objectName1));
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -16,6 +16,9 @@
package org.springframework.scheduling.concurrent;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
@@ -23,10 +26,15 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.task.AsyncListenableTaskExecutor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.InstanceOfAssertFactories.type;
/**
* Unit tests for {@link ThreadPoolTaskExecutor}.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 5.0.5
*/
class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
@@ -50,8 +58,8 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
executor.setCorePoolSize(0);
assertThat(executor.getCorePoolSize()).isEqualTo(0);
assertThat(executor.getThreadPoolExecutor().getCorePoolSize()).isEqualTo(0);
assertThat(executor.getCorePoolSize()).isZero();
assertThat(executor.getThreadPoolExecutor().getCorePoolSize()).isZero();
}
@Test
@@ -112,4 +120,37 @@ class ThreadPoolTaskExecutorTests extends AbstractSchedulingTaskExecutorTests {
assertThat(executor.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS)).isEqualTo(60);
}
@Test
void queueCapacityDefault() {
assertThat(executor.getQueueCapacity()).isEqualTo(Integer.MAX_VALUE);
assertThat(executor.getThreadPoolExecutor().getQueue())
.asInstanceOf(type(LinkedBlockingQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(Integer.MAX_VALUE);
}
@Test
void queueCapacityZero() {
executor.setQueueCapacity(0);
executor.afterPropertiesSet();
assertThat(executor.getQueueCapacity()).isZero();
assertThat(executor.getThreadPoolExecutor().getQueue())
.asInstanceOf(type(SynchronousQueue.class))
.extracting(BlockingQueue::remainingCapacity).isEqualTo(0);
}
@Test
void queueSize() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
assertThatIllegalStateException().isThrownBy(executor::getThreadPoolExecutor);
assertThat(executor.getQueueSize()).isZero();
executor.afterPropertiesSet();
assertThat(executor.getThreadPoolExecutor()).isNotNull();
assertThat(executor.getThreadPoolExecutor().getQueue()).isEmpty();
assertThat(executor.getQueueSize()).isZero();
}
}
@@ -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.
@@ -22,51 +22,50 @@ import org.junit.jupiter.api.Test;
import org.springframework.context.support.GenericXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* @author Dave Syer
*/
public class GroovyAspectIntegrationTests {
class GroovyAspectIntegrationTests {
private GenericXmlApplicationContext context;
@Test
public void testJavaBean() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-java-context.xml");
void javaBean() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName() + "-java-context.xml");
TestService bean = context.getBean("javaBean", TestService.class);
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertThat(logAdvice.getCountThrows()).isEqualTo(0);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
assertThatRuntimeException()
.isThrownBy(bean::sayHello)
.withMessage("TestServiceImpl");
assertThat(logAdvice.getCountThrows()).isEqualTo(1);
}
@Test
public void testGroovyBeanInterface() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-interface-context.xml");
void groovyBeanInterface() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName() + "-groovy-interface-context.xml");
TestService bean = context.getBean("groovyBean", TestService.class);
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertThat(logAdvice.getCountThrows()).isEqualTo(0);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
assertThatRuntimeException()
.isThrownBy(bean::sayHello)
.withMessage("GroovyServiceImpl");
assertThat(logAdvice.getCountThrows()).isEqualTo(1);
}
@Test
public void testGroovyBeanDynamic() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-dynamic-context.xml");
void groovyBeanDynamic() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName() + "-groovy-dynamic-context.xml");
TestService bean = context.getBean("groovyBean", TestService.class);
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertThat(logAdvice.getCountThrows()).isEqualTo(0);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
assertThatRuntimeException()
.isThrownBy(bean::sayHello)
.withMessage("GroovyServiceImpl");
// No proxy here because the pointcut only applies to the concrete class, not the interface
assertThat(logAdvice.getCountThrows()).isEqualTo(0);
@@ -74,21 +73,21 @@ public class GroovyAspectIntegrationTests {
}
@Test
public void testGroovyBeanProxyTargetClass() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-proxy-target-class-context.xml");
void groovyBeanProxyTargetClass() {
context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName() + "-groovy-proxy-target-class-context.xml");
TestService bean = context.getBean("groovyBean", TestService.class);
LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class);
assertThat(logAdvice.getCountThrows()).isEqualTo(0);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(
bean::sayHello)
assertThatRuntimeException()
.isThrownBy(bean::sayHello)
.withMessage("GroovyServiceImpl");
assertThat(logAdvice.getCountBefore()).isEqualTo(1);
assertThat(logAdvice.getCountThrows()).isEqualTo(1);
}
@AfterEach
public void close() {
void close() {
if (context != null) {
context.close();
}
@@ -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.
@@ -46,6 +46,7 @@ import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
@@ -318,7 +319,7 @@ public class GroovyScriptFactoryTests {
@Test
public void testWithTwoClassesDefinedInTheOneGroovyFile_WrongClassFirst() throws Exception {
assertThatExceptionOfType(Exception.class).as("two classes defined in GroovyScriptFactory source, non-Messenger class defined first").isThrownBy(() -> {
assertThatException().as("two classes defined in GroovyScriptFactory source, non-Messenger class defined first").isThrownBy(() -> {
ApplicationContext ctx = new ClassPathXmlApplicationContext("twoClassesWrongOneFirst.xml", getClass());
ctx.getBean("messenger", Messenger.class);
});
+1 -2
View File
@@ -76,8 +76,7 @@ jar {
dependsOn cglibRepackJar
from(zipTree(cglibRepackJar.archivePath)) {
include "org/springframework/cglib/**"
exclude "org/springframework/cglib/beans/BeanMap.class"
exclude "org/springframework/cglib/beans/BeanMap\$*.class"
exclude "org/springframework/cglib/beans/**"
exclude "org/springframework/cglib/core/AbstractClassGenerator*.class"
exclude "org/springframework/cglib/core/AsmApi*.class"
exclude "org/springframework/cglib/core/KeyFactory.class"
@@ -55,7 +55,7 @@ public abstract class AnnotationVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
*/
public AnnotationVisitor(final int api) {
protected AnnotationVisitor(final int api) {
this(api, null);
}
@@ -67,7 +67,7 @@ public abstract class AnnotationVisitor {
* @param annotationVisitor the annotation visitor to which this visitor must delegate method
* calls. May be {@literal null}.
*/
public AnnotationVisitor(final int api, final AnnotationVisitor annotationVisitor) {
protected AnnotationVisitor(final int api, final AnnotationVisitor annotationVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
&& api != Opcodes.ASM7
@@ -65,6 +65,15 @@ public class ByteVector {
this.length = data.length;
}
/**
* Returns the actual number of bytes in this vector.
*
* @return the actual number of bytes in this vector.
*/
public int size() {
return length;
}
/**
* Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.
*
@@ -54,7 +54,7 @@ public abstract class ClassVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
*/
public ClassVisitor(final int api) {
protected ClassVisitor(final int api) {
this(api, null);
}
@@ -66,7 +66,7 @@ public abstract class ClassVisitor {
* @param classVisitor the class visitor to which this visitor must delegate method calls. May be
* null.
*/
public ClassVisitor(final int api, final ClassVisitor classVisitor) {
protected ClassVisitor(final int api, final ClassVisitor classVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
&& api != Opcodes.ASM7
@@ -51,7 +51,7 @@ public abstract class FieldVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
*/
public FieldVisitor(final int api) {
protected FieldVisitor(final int api) {
this(api, null);
}
@@ -63,7 +63,7 @@ public abstract class FieldVisitor {
* @param fieldVisitor the field visitor to which this visitor must delegate method calls. May be
* null.
*/
public FieldVisitor(final int api, final FieldVisitor fieldVisitor) {
protected FieldVisitor(final int api, final FieldVisitor fieldVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
&& api != Opcodes.ASM7
@@ -67,7 +67,7 @@ public abstract class MethodVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of the {@code
* ASM}<i>x</i> values in {@link Opcodes}.
*/
public MethodVisitor(final int api) {
protected MethodVisitor(final int api) {
this(api, null);
}
@@ -79,7 +79,7 @@ public abstract class MethodVisitor {
* @param methodVisitor the method visitor to which this visitor must delegate method calls. May
* be null.
*/
public MethodVisitor(final int api, final MethodVisitor methodVisitor) {
protected MethodVisitor(final int api, final MethodVisitor methodVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
&& api != Opcodes.ASM7
@@ -349,12 +349,12 @@ public abstract class MethodVisitor {
*
* @param opcode the opcode of the local variable instruction to be visited. This opcode is either
* ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, LSTORE, FSTORE, DSTORE, ASTORE or RET.
* @param var the operand of the instruction to be visited. This operand is the index of a local
* variable.
* @param varIndex the operand of the instruction to be visited. This operand is the index of a
* local variable.
*/
public void visitVarInsn(final int opcode, final int var) {
public void visitVarInsn(final int opcode, final int varIndex) {
if (mv != null) {
mv.visitVarInsn(opcode, var);
mv.visitVarInsn(opcode, varIndex);
}
}
@@ -466,7 +466,8 @@ final class MethodWriter extends MethodVisitor {
/**
* Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link
* #COMPUTE_INSERTED_FRAMES}, {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.
* #COMPUTE_INSERTED_FRAMES}, {@link COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link
* #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.
*/
private final int compute;
@@ -904,26 +905,26 @@ final class MethodWriter extends MethodVisitor {
}
@Override
public void visitVarInsn(final int opcode, final int var) {
public void visitVarInsn(final int opcode, final int varIndex) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
if (var < 4 && opcode != Opcodes.RET) {
if (varIndex < 4 && opcode != Opcodes.RET) {
int optimizedOpcode;
if (opcode < Opcodes.ISTORE) {
optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + var;
optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + varIndex;
} else {
optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + var;
optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + varIndex;
}
code.putByte(optimizedOpcode);
} else if (var >= 256) {
code.putByte(Constants.WIDE).put12(opcode, var);
} else if (varIndex >= 256) {
code.putByte(Constants.WIDE).put12(opcode, varIndex);
} else {
code.put11(opcode, var);
code.put11(opcode, varIndex);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null) {
if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
currentBasicBlock.frame.execute(opcode, var, null, null);
currentBasicBlock.frame.execute(opcode, varIndex, null, null);
} else {
if (opcode == Opcodes.RET) {
// No stack size delta.
@@ -945,9 +946,9 @@ final class MethodWriter extends MethodVisitor {
|| opcode == Opcodes.DLOAD
|| opcode == Opcodes.LSTORE
|| opcode == Opcodes.DSTORE) {
currentMaxLocals = var + 2;
currentMaxLocals = varIndex + 2;
} else {
currentMaxLocals = var + 1;
currentMaxLocals = varIndex + 1;
}
if (currentMaxLocals > maxLocals) {
maxLocals = currentMaxLocals;
@@ -1307,21 +1308,21 @@ final class MethodWriter extends MethodVisitor {
}
@Override
public void visitIincInsn(final int var, final int increment) {
public void visitIincInsn(final int varIndex, final int increment) {
lastBytecodeOffset = code.length;
// Add the instruction to the bytecode of the method.
if ((var > 255) || (increment > 127) || (increment < -128)) {
code.putByte(Constants.WIDE).put12(Opcodes.IINC, var).putShort(increment);
if ((varIndex > 255) || (increment > 127) || (increment < -128)) {
code.putByte(Constants.WIDE).put12(Opcodes.IINC, varIndex).putShort(increment);
} else {
code.putByte(Opcodes.IINC).put11(var, increment);
code.putByte(Opcodes.IINC).put11(varIndex, increment);
}
// If needed, update the maximum stack size and number of locals, and stack map frames.
if (currentBasicBlock != null
&& (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) {
currentBasicBlock.frame.execute(Opcodes.IINC, var, null, null);
currentBasicBlock.frame.execute(Opcodes.IINC, varIndex, null, null);
}
if (compute != COMPUTE_NOTHING) {
int currentMaxLocals = var + 1;
int currentMaxLocals = varIndex + 1;
if (currentMaxLocals > maxLocals) {
maxLocals = currentMaxLocals;
}
@@ -53,7 +53,7 @@ public abstract class ModuleVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM6}
* or {@link Opcodes#ASM7}.
*/
public ModuleVisitor(final int api) {
protected ModuleVisitor(final int api) {
this(api, null);
}
@@ -65,7 +65,7 @@ public abstract class ModuleVisitor {
* @param moduleVisitor the module visitor to which this visitor must delegate method calls. May
* be null.
*/
public ModuleVisitor(final int api, final ModuleVisitor moduleVisitor) {
protected ModuleVisitor(final int api, final ModuleVisitor moduleVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
&& api != Opcodes.ASM7
@@ -53,7 +53,7 @@ public abstract class RecordComponentVisitor {
* @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM8}
* or {@link Opcodes#ASM9}.
*/
public RecordComponentVisitor(final int api) {
protected RecordComponentVisitor(final int api) {
this(api, null);
}
@@ -64,7 +64,7 @@ public abstract class RecordComponentVisitor {
* @param recordComponentVisitor the record component visitor to which this visitor must delegate
* method calls. May be null.
*/
public RecordComponentVisitor(
protected RecordComponentVisitor(
final int api, final RecordComponentVisitor recordComponentVisitor) {
if (api != Opcodes.ASM9
&& api != Opcodes.ASM8
@@ -440,7 +440,7 @@ public final class Type {
case '(':
return new Type(METHOD, descriptorBuffer, descriptorBegin, descriptorEnd);
default:
throw new IllegalArgumentException();
throw new IllegalArgumentException("Invalid descriptor: " + descriptorBuffer);
}
}
@@ -0,0 +1,179 @@
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.security.ProtectionDomain;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.Type;
import java.util.*;
/**
* @author Chris Nokleberg
*/
@SuppressWarnings({"rawtypes", "unchecked"})
abstract public class BeanCopier
{
private static final BeanCopierKey KEY_FACTORY =
(BeanCopierKey)KeyFactory.create(BeanCopierKey.class);
private static final Type CONVERTER =
TypeUtils.parseType("org.springframework.cglib.core.Converter");
private static final Type BEAN_COPIER =
TypeUtils.parseType("org.springframework.cglib.beans.BeanCopier");
private static final Signature COPY =
new Signature("copy", Type.VOID_TYPE, new Type[]{ Constants.TYPE_OBJECT, Constants.TYPE_OBJECT, CONVERTER });
private static final Signature CONVERT =
TypeUtils.parseSignature("Object convert(Object, Class, Object)");
interface BeanCopierKey {
public Object newInstance(String source, String target, boolean useConverter);
}
public static BeanCopier create(Class source, Class target, boolean useConverter) {
Generator gen = new Generator();
gen.setSource(source);
gen.setTarget(target);
gen.setUseConverter(useConverter);
return gen.create();
}
abstract public void copy(Object from, Object to, Converter converter);
public static class Generator extends AbstractClassGenerator {
private static final Source SOURCE = new Source(BeanCopier.class.getName());
private Class source;
private Class target;
private boolean useConverter;
public Generator() {
super(SOURCE);
}
public void setSource(Class source) {
if(!Modifier.isPublic(source.getModifiers())){
setNamePrefix(source.getName());
}
this.source = source;
}
public void setTarget(Class target) {
if(!Modifier.isPublic(target.getModifiers())){
setNamePrefix(target.getName());
}
this.target = target;
// SPRING PATCH BEGIN
setContextClass(target);
// SPRING PATCH END
}
public void setUseConverter(boolean useConverter) {
this.useConverter = useConverter;
}
protected ClassLoader getDefaultClassLoader() {
return source.getClassLoader();
}
protected ProtectionDomain getProtectionDomain() {
return ReflectUtils.getProtectionDomain(source);
}
public BeanCopier create() {
Object key = KEY_FACTORY.newInstance(source.getName(), target.getName(), useConverter);
return (BeanCopier)super.create(key);
}
public void generateClass(ClassVisitor v) {
Type sourceType = Type.getType(source);
Type targetType = Type.getType(target);
ClassEmitter ce = new ClassEmitter(v);
ce.begin_class(Constants.V1_8,
Constants.ACC_PUBLIC,
getClassName(),
BEAN_COPIER,
null,
Constants.SOURCE_FILE);
EmitUtils.null_constructor(ce);
CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, COPY, null);
PropertyDescriptor[] getters = ReflectUtils.getBeanGetters(source);
PropertyDescriptor[] setters = ReflectUtils.getBeanSetters(target);
Map names = new HashMap();
for (int i = 0; i < getters.length; i++) {
names.put(getters[i].getName(), getters[i]);
}
Local targetLocal = e.make_local();
Local sourceLocal = e.make_local();
if (useConverter) {
e.load_arg(1);
e.checkcast(targetType);
e.store_local(targetLocal);
e.load_arg(0);
e.checkcast(sourceType);
e.store_local(sourceLocal);
} else {
e.load_arg(1);
e.checkcast(targetType);
e.load_arg(0);
e.checkcast(sourceType);
}
for (int i = 0; i < setters.length; i++) {
PropertyDescriptor setter = setters[i];
PropertyDescriptor getter = (PropertyDescriptor)names.get(setter.getName());
if (getter != null) {
MethodInfo read = ReflectUtils.getMethodInfo(getter.getReadMethod());
MethodInfo write = ReflectUtils.getMethodInfo(setter.getWriteMethod());
if (useConverter) {
Type setterType = write.getSignature().getArgumentTypes()[0];
e.load_local(targetLocal);
e.load_arg(2);
e.load_local(sourceLocal);
e.invoke(read);
e.box(read.getSignature().getReturnType());
EmitUtils.load_class(e, setterType);
e.push(write.getSignature().getName());
e.invoke_interface(CONVERTER, CONVERT);
e.unbox_or_zero(setterType);
e.invoke(write);
} else if (compatible(getter, setter)) {
e.dup2();
e.invoke(read);
e.invoke(write);
}
}
}
e.return_value();
e.end_method();
ce.end_class();
}
private static boolean compatible(PropertyDescriptor getter, PropertyDescriptor setter) {
// TODO: allow automatic widening conversions?
return setter.getPropertyType().isAssignableFrom(getter.getPropertyType());
}
protected Object firstInstance(Class type) {
return ReflectUtils.newInstance(type);
}
protected Object nextInstance(Object instance) {
return instance;
}
}
}
@@ -0,0 +1,153 @@
/*
* Copyright 2003 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.beans.PropertyDescriptor;
import java.security.ProtectionDomain;
import java.util.*;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.Type;
/**
* @author Juozas Baliuka, Chris Nokleberg
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class BeanGenerator extends AbstractClassGenerator
{
private static final Source SOURCE = new Source(BeanGenerator.class.getName());
private static final BeanGeneratorKey KEY_FACTORY =
(BeanGeneratorKey)KeyFactory.create(BeanGeneratorKey.class);
interface BeanGeneratorKey {
public Object newInstance(String superclass, Map props);
}
private Class superclass;
private Map props = new HashMap();
private boolean classOnly;
public BeanGenerator() {
super(SOURCE);
}
/**
* Set the class which the generated class will extend. The class
* must not be declared as final, and must have a non-private
* no-argument constructor.
* @param superclass class to extend, or null to extend Object
*/
public void setSuperclass(Class superclass) {
if (superclass != null && superclass.equals(Object.class)) {
superclass = null;
}
this.superclass = superclass;
// SPRING PATCH BEGIN
setContextClass(superclass);
// SPRING PATCH END
}
public void addProperty(String name, Class type) {
if (props.containsKey(name)) {
throw new IllegalArgumentException("Duplicate property name \"" + name + "\"");
}
props.put(name, Type.getType(type));
}
protected ClassLoader getDefaultClassLoader() {
if (superclass != null) {
return superclass.getClassLoader();
} else {
return null;
}
}
protected ProtectionDomain getProtectionDomain() {
return ReflectUtils.getProtectionDomain(superclass);
}
public Object create() {
classOnly = false;
return createHelper();
}
public Object createClass() {
classOnly = true;
return createHelper();
}
private Object createHelper() {
if (superclass != null) {
setNamePrefix(superclass.getName());
}
String superName = (superclass != null) ? superclass.getName() : "java.lang.Object";
Object key = KEY_FACTORY.newInstance(superName, props);
return super.create(key);
}
public void generateClass(ClassVisitor v) throws Exception {
int size = props.size();
String[] names = (String[])props.keySet().toArray(new String[size]);
Type[] types = new Type[size];
for (int i = 0; i < size; i++) {
types[i] = (Type)props.get(names[i]);
}
ClassEmitter ce = new ClassEmitter(v);
ce.begin_class(Constants.V1_8,
Constants.ACC_PUBLIC,
getClassName(),
superclass != null ? Type.getType(superclass) : Constants.TYPE_OBJECT,
null,
null);
EmitUtils.null_constructor(ce);
EmitUtils.add_properties(ce, names, types);
ce.end_class();
}
protected Object firstInstance(Class type) {
if (classOnly) {
return type;
} else {
return ReflectUtils.newInstance(type);
}
}
protected Object nextInstance(Object instance) {
Class protoclass = (instance instanceof Class) ? (Class)instance : instance.getClass();
if (classOnly) {
return protoclass;
} else {
return ReflectUtils.newInstance(protoclass);
}
}
public static void addProperties(BeanGenerator gen, Map props) {
for (Iterator it = props.keySet().iterator(); it.hasNext();) {
String name = (String)it.next();
gen.addProperty(name, (Class)props.get(name));
}
}
public static void addProperties(BeanGenerator gen, Class type) {
addProperties(gen, ReflectUtils.getBeanProperties(type));
}
public static void addProperties(BeanGenerator gen, PropertyDescriptor[] descriptors) {
for (int i = 0; i < descriptors.length; i++) {
gen.addProperty(descriptors[i].getName(), descriptors[i].getPropertyType());
}
}
}
@@ -97,7 +97,9 @@ abstract public class BeanMap implements Map {
this.bean = bean;
if (bean != null) {
beanClass = bean.getClass();
// SPRING PATCH BEGIN
setContextClass(beanClass);
// SPRING PATCH END
}
}
@@ -0,0 +1,193 @@
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.beans.*;
import java.util.*;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.Label;
import org.springframework.asm.Type;
@SuppressWarnings({"rawtypes", "unchecked"})
class BeanMapEmitter extends ClassEmitter {
private static final Type BEAN_MAP =
TypeUtils.parseType("org.springframework.cglib.beans.BeanMap");
private static final Type FIXED_KEY_SET =
TypeUtils.parseType("org.springframework.cglib.beans.FixedKeySet");
private static final Signature CSTRUCT_OBJECT =
TypeUtils.parseConstructor("Object");
private static final Signature CSTRUCT_STRING_ARRAY =
TypeUtils.parseConstructor("String[]");
private static final Signature BEAN_MAP_GET =
TypeUtils.parseSignature("Object get(Object, Object)");
private static final Signature BEAN_MAP_PUT =
TypeUtils.parseSignature("Object put(Object, Object, Object)");
private static final Signature KEY_SET =
TypeUtils.parseSignature("java.util.Set keySet()");
private static final Signature NEW_INSTANCE =
new Signature("newInstance", BEAN_MAP, new Type[]{ Constants.TYPE_OBJECT });
private static final Signature GET_PROPERTY_TYPE =
TypeUtils.parseSignature("Class getPropertyType(String)");
public BeanMapEmitter(ClassVisitor v, String className, Class type, int require) {
super(v);
begin_class(Constants.V1_8, Constants.ACC_PUBLIC, className, BEAN_MAP, null, Constants.SOURCE_FILE);
EmitUtils.null_constructor(this);
EmitUtils.factory_method(this, NEW_INSTANCE);
generateConstructor();
Map getters = makePropertyMap(ReflectUtils.getBeanGetters(type));
Map setters = makePropertyMap(ReflectUtils.getBeanSetters(type));
Map allProps = new HashMap();
allProps.putAll(getters);
allProps.putAll(setters);
if (require != 0) {
for (Iterator it = allProps.keySet().iterator(); it.hasNext();) {
String name = (String)it.next();
if ((((require & BeanMap.REQUIRE_GETTER) != 0) && !getters.containsKey(name)) ||
(((require & BeanMap.REQUIRE_SETTER) != 0) && !setters.containsKey(name))) {
it.remove();
getters.remove(name);
setters.remove(name);
}
}
}
generateGet(type, getters);
generatePut(type, setters);
String[] allNames = getNames(allProps);
generateKeySet(allNames);
generateGetPropertyType(allProps, allNames);
end_class();
}
private Map makePropertyMap(PropertyDescriptor[] props) {
Map names = new HashMap();
for (int i = 0; i < props.length; i++) {
names.put(props[i].getName(), props[i]);
}
return names;
}
private String[] getNames(Map propertyMap) {
return (String[])propertyMap.keySet().toArray(new String[propertyMap.size()]);
}
private void generateConstructor() {
CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT, null);
e.load_this();
e.load_arg(0);
e.super_invoke_constructor(CSTRUCT_OBJECT);
e.return_value();
e.end_method();
}
private void generateGet(Class type, final Map getters) {
final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, BEAN_MAP_GET, null);
e.load_arg(0);
e.checkcast(Type.getType(type));
e.load_arg(1);
e.checkcast(Constants.TYPE_STRING);
EmitUtils.string_switch(e, getNames(getters), Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() {
public void processCase(Object key, Label end) {
PropertyDescriptor pd = (PropertyDescriptor)getters.get(key);
MethodInfo method = ReflectUtils.getMethodInfo(pd.getReadMethod());
e.invoke(method);
e.box(method.getSignature().getReturnType());
e.return_value();
}
public void processDefault() {
e.aconst_null();
e.return_value();
}
});
e.end_method();
}
private void generatePut(Class type, final Map setters) {
final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, BEAN_MAP_PUT, null);
e.load_arg(0);
e.checkcast(Type.getType(type));
e.load_arg(1);
e.checkcast(Constants.TYPE_STRING);
EmitUtils.string_switch(e, getNames(setters), Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() {
public void processCase(Object key, Label end) {
PropertyDescriptor pd = (PropertyDescriptor)setters.get(key);
if (pd.getReadMethod() == null) {
e.aconst_null();
} else {
MethodInfo read = ReflectUtils.getMethodInfo(pd.getReadMethod());
e.dup();
e.invoke(read);
e.box(read.getSignature().getReturnType());
}
e.swap(); // move old value behind bean
e.load_arg(2); // new value
MethodInfo write = ReflectUtils.getMethodInfo(pd.getWriteMethod());
e.unbox(write.getSignature().getArgumentTypes()[0]);
e.invoke(write);
e.return_value();
}
public void processDefault() {
// fall-through
}
});
e.aconst_null();
e.return_value();
e.end_method();
}
private void generateKeySet(String[] allNames) {
// static initializer
declare_field(Constants.ACC_STATIC | Constants.ACC_PRIVATE, "keys", FIXED_KEY_SET, null);
CodeEmitter e = begin_static();
e.new_instance(FIXED_KEY_SET);
e.dup();
EmitUtils.push_array(e, allNames);
e.invoke_constructor(FIXED_KEY_SET, CSTRUCT_STRING_ARRAY);
e.putfield("keys");
e.return_value();
e.end_method();
// keySet
e = begin_method(Constants.ACC_PUBLIC, KEY_SET, null);
e.load_this();
e.getfield("keys");
e.return_value();
e.end_method();
}
private void generateGetPropertyType(final Map allProps, String[] allNames) {
final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, GET_PROPERTY_TYPE, null);
e.load_arg(0);
EmitUtils.string_switch(e, allNames, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() {
public void processCase(Object key, Label end) {
PropertyDescriptor pd = (PropertyDescriptor)allProps.get(key);
EmitUtils.load_class(e, Type.getType(pd.getPropertyType()));
e.return_value();
}
public void processDefault() {
e.aconst_null();
e.return_value();
}
});
e.end_method();
}
}
@@ -0,0 +1,146 @@
/*
* Copyright 2003 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.*;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
/**
* @author Juozas Baliuka
*/
@SuppressWarnings({"rawtypes", "unchecked"})
abstract public class BulkBean
{
private static final BulkBeanKey KEY_FACTORY =
(BulkBeanKey)KeyFactory.create(BulkBeanKey.class);
interface BulkBeanKey {
public Object newInstance(String target, String[] getters, String[] setters, String[] types);
}
protected Class target;
protected String[] getters, setters;
protected Class[] types;
protected BulkBean() { }
abstract public void getPropertyValues(Object bean, Object[] values);
abstract public void setPropertyValues(Object bean, Object[] values);
public Object[] getPropertyValues(Object bean) {
Object[] values = new Object[getters.length];
getPropertyValues(bean, values);
return values;
}
public Class[] getPropertyTypes() {
return types.clone();
}
public String[] getGetters() {
return getters.clone();
}
public String[] getSetters() {
return setters.clone();
}
public static BulkBean create(Class target, String[] getters, String[] setters, Class[] types) {
Generator gen = new Generator();
gen.setTarget(target);
gen.setGetters(getters);
gen.setSetters(setters);
gen.setTypes(types);
return gen.create();
}
public static class Generator extends AbstractClassGenerator {
private static final Source SOURCE = new Source(BulkBean.class.getName());
private Class target;
private String[] getters;
private String[] setters;
private Class[] types;
public Generator() {
super(SOURCE);
}
public void setTarget(Class target) {
this.target = target;
// SPRING PATCH BEGIN
setContextClass(target);
// SPRING PATCH END
}
public void setGetters(String[] getters) {
this.getters = getters;
}
public void setSetters(String[] setters) {
this.setters = setters;
}
public void setTypes(Class[] types) {
this.types = types;
}
protected ClassLoader getDefaultClassLoader() {
return target.getClassLoader();
}
protected ProtectionDomain getProtectionDomain() {
return ReflectUtils.getProtectionDomain(target);
}
public BulkBean create() {
setNamePrefix(target.getName());
String targetClassName = target.getName();
String[] typeClassNames = ReflectUtils.getNames(types);
Object key = KEY_FACTORY.newInstance(targetClassName, getters, setters, typeClassNames);
return (BulkBean)super.create(key);
}
public void generateClass(ClassVisitor v) throws Exception {
new BulkBeanEmitter(v, getClassName(), target, getters, setters, types);
}
protected Object firstInstance(Class type) {
BulkBean instance = (BulkBean)ReflectUtils.newInstance(type);
instance.target = target;
int length = getters.length;
instance.getters = new String[length];
System.arraycopy(getters, 0, instance.getters, 0, length);
instance.setters = new String[length];
System.arraycopy(setters, 0, instance.setters, 0, length);
instance.types = new Class[types.length];
System.arraycopy(types, 0, instance.types, 0, types.length);
return instance;
}
protected Object nextInstance(Object instance) {
return instance;
}
}
}
@@ -0,0 +1,157 @@
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.Type;
@SuppressWarnings({"rawtypes", "unchecked"})
class BulkBeanEmitter extends ClassEmitter {
private static final Signature GET_PROPERTY_VALUES =
TypeUtils.parseSignature("void getPropertyValues(Object, Object[])");
private static final Signature SET_PROPERTY_VALUES =
TypeUtils.parseSignature("void setPropertyValues(Object, Object[])");
private static final Signature CSTRUCT_EXCEPTION =
TypeUtils.parseConstructor("Throwable, int");
private static final Type BULK_BEAN =
TypeUtils.parseType("org.springframework.cglib.beans.BulkBean");
private static final Type BULK_BEAN_EXCEPTION =
TypeUtils.parseType("org.springframework.cglib.beans.BulkBeanException");
public BulkBeanEmitter(ClassVisitor v,
String className,
Class target,
String[] getterNames,
String[] setterNames,
Class[] types) {
super(v);
Method[] getters = new Method[getterNames.length];
Method[] setters = new Method[setterNames.length];
validate(target, getterNames, setterNames, types, getters, setters);
begin_class(Constants.V1_8, Constants.ACC_PUBLIC, className, BULK_BEAN, null, Constants.SOURCE_FILE);
EmitUtils.null_constructor(this);
generateGet(target, getters);
generateSet(target, setters);
end_class();
}
private void generateGet(final Class target, final Method[] getters) {
CodeEmitter e = begin_method(Constants.ACC_PUBLIC, GET_PROPERTY_VALUES, null);
if (getters.length > 0) {
e.load_arg(0);
e.checkcast(Type.getType(target));
Local bean = e.make_local();
e.store_local(bean);
for (int i = 0; i < getters.length; i++) {
if (getters[i] != null) {
MethodInfo getter = ReflectUtils.getMethodInfo(getters[i]);
e.load_arg(1);
e.push(i);
e.load_local(bean);
e.invoke(getter);
e.box(getter.getSignature().getReturnType());
e.aastore();
}
}
}
e.return_value();
e.end_method();
}
private void generateSet(final Class target, final Method[] setters) {
// setPropertyValues
CodeEmitter e = begin_method(Constants.ACC_PUBLIC, SET_PROPERTY_VALUES, null);
if (setters.length > 0) {
Local index = e.make_local(Type.INT_TYPE);
e.push(0);
e.store_local(index);
e.load_arg(0);
e.checkcast(Type.getType(target));
e.load_arg(1);
Block handler = e.begin_block();
int lastIndex = 0;
for (int i = 0; i < setters.length; i++) {
if (setters[i] != null) {
MethodInfo setter = ReflectUtils.getMethodInfo(setters[i]);
int diff = i - lastIndex;
if (diff > 0) {
e.iinc(index, diff);
lastIndex = i;
}
e.dup2();
e.aaload(i);
e.unbox(setter.getSignature().getArgumentTypes()[0]);
e.invoke(setter);
}
}
handler.end();
e.return_value();
e.catch_exception(handler, Constants.TYPE_THROWABLE);
e.new_instance(BULK_BEAN_EXCEPTION);
e.dup_x1();
e.swap();
e.load_local(index);
e.invoke_constructor(BULK_BEAN_EXCEPTION, CSTRUCT_EXCEPTION);
e.athrow();
} else {
e.return_value();
}
e.end_method();
}
private static void validate(Class target,
String[] getters,
String[] setters,
Class[] types,
Method[] getters_out,
Method[] setters_out) {
int i = -1;
if (setters.length != types.length || getters.length != types.length) {
throw new BulkBeanException("accessor array length must be equal type array length", i);
}
try {
for (i = 0; i < types.length; i++) {
if (getters[i] != null) {
Method method = ReflectUtils.findDeclaredMethod(target, getters[i], null);
if (method.getReturnType() != types[i]) {
throw new BulkBeanException("Specified type " + types[i] +
" does not match declared type " + method.getReturnType(), i);
}
if (Modifier.isPrivate(method.getModifiers())) {
throw new BulkBeanException("Property is private", i);
}
getters_out[i] = method;
}
if (setters[i] != null) {
Method method = ReflectUtils.findDeclaredMethod(target, setters[i], new Class[]{ types[i] });
if (Modifier.isPrivate(method.getModifiers()) ){
throw new BulkBeanException("Property is private", i);
}
setters_out[i] = method;
}
}
} catch (NoSuchMethodException e) {
throw new BulkBeanException("Cannot find specified property", i);
}
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2003 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import org.springframework.cglib.core.CodeGenerationException;
@SuppressWarnings({"rawtypes", "unchecked", "serial"})
public class BulkBeanException extends RuntimeException
{
private int index;
private Throwable cause;
public BulkBeanException(String message, int index) {
super(message);
this.index = index;
}
public BulkBeanException(Throwable cause, int index) {
super(cause.getMessage());
this.index = index;
this.cause = cause;
}
public int getIndex() {
return index;
}
public Throwable getCause() {
return cause;
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2003 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.util.*;
@SuppressWarnings({"rawtypes", "unchecked"})
public /* need it for class loading */ class FixedKeySet extends AbstractSet {
private Set set;
private int size;
public FixedKeySet(String[] keys) {
size = keys.length;
set = Collections.unmodifiableSet(new HashSet(Arrays.asList(keys)));
}
public Iterator iterator() {
return set.iterator();
}
public int size() {
return size;
}
}
@@ -0,0 +1,132 @@
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.beans;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import org.springframework.cglib.core.*;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.Type;
/**
* @author Chris Nokleberg
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class ImmutableBean
{
private static final Type ILLEGAL_STATE_EXCEPTION =
TypeUtils.parseType("IllegalStateException");
private static final Signature CSTRUCT_OBJECT =
TypeUtils.parseConstructor("Object");
private static final Class[] OBJECT_CLASSES = { Object.class };
private static final String FIELD_NAME = "CGLIB$RWBean";
private ImmutableBean() {
}
public static Object create(Object bean) {
Generator gen = new Generator();
gen.setBean(bean);
return gen.create();
}
public static class Generator extends AbstractClassGenerator {
private static final Source SOURCE = new Source(ImmutableBean.class.getName());
private Object bean;
private Class target;
public Generator() {
super(SOURCE);
}
public void setBean(Object bean) {
this.bean = bean;
target = bean.getClass();
// SPRING PATCH BEGIN
setContextClass(target);
// SPRING PATCH END
}
protected ClassLoader getDefaultClassLoader() {
return target.getClassLoader();
}
protected ProtectionDomain getProtectionDomain() {
return ReflectUtils.getProtectionDomain(target);
}
public Object create() {
String name = target.getName();
setNamePrefix(name);
return super.create(name);
}
public void generateClass(ClassVisitor v) {
Type targetType = Type.getType(target);
ClassEmitter ce = new ClassEmitter(v);
ce.begin_class(Constants.V1_8,
Constants.ACC_PUBLIC,
getClassName(),
targetType,
null,
Constants.SOURCE_FILE);
ce.declare_field(Constants.ACC_FINAL | Constants.ACC_PRIVATE, FIELD_NAME, targetType, null);
CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT, null);
e.load_this();
e.super_invoke_constructor();
e.load_this();
e.load_arg(0);
e.checkcast(targetType);
e.putfield(FIELD_NAME);
e.return_value();
e.end_method();
PropertyDescriptor[] descriptors = ReflectUtils.getBeanProperties(target);
Method[] getters = ReflectUtils.getPropertyMethods(descriptors, true, false);
Method[] setters = ReflectUtils.getPropertyMethods(descriptors, false, true);
for (int i = 0; i < getters.length; i++) {
MethodInfo getter = ReflectUtils.getMethodInfo(getters[i]);
e = EmitUtils.begin_method(ce, getter, Constants.ACC_PUBLIC);
e.load_this();
e.getfield(FIELD_NAME);
e.invoke(getter);
e.return_value();
e.end_method();
}
for (int i = 0; i < setters.length; i++) {
MethodInfo setter = ReflectUtils.getMethodInfo(setters[i]);
e = EmitUtils.begin_method(ce, setter, Constants.ACC_PUBLIC);
e.throw_exception(ILLEGAL_STATE_EXCEPTION, "Bean is immutable");
e.end_method();
}
ce.end_class();
}
protected Object firstInstance(Class type) {
return ReflectUtils.newInstance(type, OBJECT_CLASSES, new Object[]{ bean });
}
// TODO: optimize
protected Object nextInstance(Object instance) {
return firstInstance(instance.getClass());
}
}
}
@@ -1,6 +1,6 @@
/**
* Spring's repackaging of the
* <a href="http://cglib.sourceforge.net">CGLIB</a> beans package
* <a href="https://github.com/cglib/cglib">CGLIB</a> beans package
* (for internal use only).
*
* <p>As this repackaging happens at the class file level, sources
@@ -1,6 +1,6 @@
/**
* Spring's repackaging of the
* <a href="http://cglib.sourceforge.net">CGLIB</a> core package
* <a href="https://github.com/cglib/cglib">CGLIB</a> core package
* (for internal use only).
*
* <p>As this repackaging happens at the class file level, sources
@@ -1,6 +1,6 @@
/**
* Spring's repackaging of the
* <a href="http://cglib.sourceforge.net">CGLIB</a> proxy package
* <a href="https://github.com/cglib/cglib">CGLIB</a> proxy package
* (for internal use only).
*
* <p>As this repackaging happens at the class file level, sources
@@ -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.
@@ -17,8 +17,8 @@
package org.springframework.core.convert.support;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
@@ -41,21 +41,27 @@ import org.springframework.util.ReflectionUtils;
* <h3>Conversion Algorithm</h3>
* <ol>
* <li>Invoke a non-static {@code to[targetType.simpleName]()} method on the
* source object that has a return type equal to {@code targetType}, if such
* source object that has a return type assignable to {@code targetType}, if such
* a method exists. For example, {@code org.example.Bar Foo#toBar()} is a
* method that follows this convention.
* <li>Otherwise invoke a <em>static</em> {@code valueOf(sourceType)} or Java
* 8 style <em>static</em> {@code of(sourceType)} or {@code from(sourceType)}
* method on the {@code targetType}, if such a method exists.
* method on the {@code targetType} that has a return type <em>related</em> to
* {@code targetType}, if such a method exists. For example, a static
* {@code Foo.of(sourceType)} method that returns a {@code Foo},
* {@code SuperFooType}, or {@code SubFooType} is a method that follows this
* convention. {@link java.time.ZoneId#of(String)} is a concrete example of
* such a static factory method which returns a subtype of {@code ZoneId}.
* <li>Otherwise invoke a constructor on the {@code targetType} that accepts
* a single {@code sourceType} argument, if such a constructor exists.
* <li>Otherwise throw a {@link ConversionFailedException}.
* <li>Otherwise throw a {@link ConversionFailedException} or
* {@link IllegalStateException}.
* </ol>
*
* <p><strong>Warning</strong>: this converter does <em>not</em> support the
* {@link Object#toString()} method for converting from a {@code sourceType}
* to {@code java.lang.String}. For {@code toString()} support, use
* {@link FallbackObjectToStringConverter} instead.
* {@link Object#toString()} or {@link String#valueOf(Object)} methods for converting
* from a {@code sourceType} to {@code java.lang.String}. For {@code toString()}
* support, use {@link FallbackObjectToStringConverter} instead.
*
* @author Keith Donald
* @author Juergen Hoeller
@@ -65,8 +71,9 @@ import org.springframework.util.ReflectionUtils;
*/
final class ObjectToObjectConverter implements ConditionalGenericConverter {
// Cache for the latest to-method resolved on a given Class
private static final Map<Class<?>, Member> conversionMemberCache =
// Cache for the latest to-method, static factory method, or factory constructor
// resolved on a given Class
private static final Map<Class<?>, Executable> conversionExecutableCache =
new ConcurrentReferenceHashMap<>(32);
@@ -89,11 +96,11 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
}
Class<?> sourceClass = sourceType.getType();
Class<?> targetClass = targetType.getType();
Member member = getValidatedMember(targetClass, sourceClass);
Executable executable = getValidatedExecutable(targetClass, sourceClass);
try {
if (member instanceof Method) {
Method method = (Method) member;
if (executable instanceof Method) {
Method method = (Method) executable;
ReflectionUtils.makeAccessible(method);
if (!Modifier.isStatic(method.getModifiers())) {
return method.invoke(source);
@@ -102,8 +109,8 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
return method.invoke(null, source);
}
}
else if (member instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) member;
else if (executable instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) executable;
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(source);
}
@@ -124,42 +131,41 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
}
static boolean hasConversionMethodOrConstructor(Class<?> targetClass, Class<?> sourceClass) {
return (getValidatedMember(targetClass, sourceClass) != null);
return (getValidatedExecutable(targetClass, sourceClass) != null);
}
@Nullable
private static Member getValidatedMember(Class<?> targetClass, Class<?> sourceClass) {
Member member = conversionMemberCache.get(targetClass);
if (isApplicable(member, sourceClass)) {
return member;
private static Executable getValidatedExecutable(Class<?> targetClass, Class<?> sourceClass) {
Executable executable = conversionExecutableCache.get(targetClass);
if (isApplicable(executable, sourceClass)) {
return executable;
}
member = determineToMethod(targetClass, sourceClass);
if (member == null) {
member = determineFactoryMethod(targetClass, sourceClass);
if (member == null) {
member = determineFactoryConstructor(targetClass, sourceClass);
if (member == null) {
executable = determineToMethod(targetClass, sourceClass);
if (executable == null) {
executable = determineFactoryMethod(targetClass, sourceClass);
if (executable == null) {
executable = determineFactoryConstructor(targetClass, sourceClass);
if (executable == null) {
return null;
}
}
}
conversionMemberCache.put(targetClass, member);
return member;
conversionExecutableCache.put(targetClass, executable);
return executable;
}
private static boolean isApplicable(Member member, Class<?> sourceClass) {
if (member instanceof Method) {
Method method = (Method) member;
private static boolean isApplicable(Executable executable, Class<?> sourceClass) {
if (executable instanceof Method) {
Method method = (Method) executable;
return (!Modifier.isStatic(method.getModifiers()) ?
ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
method.getParameterTypes()[0] == sourceClass);
}
else if (member instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) member;
else if (executable instanceof Constructor) {
Constructor<?> ctor = (Constructor<?>) executable;
return (ctor.getParameterTypes()[0] == sourceClass);
}
else {
@@ -193,7 +199,18 @@ final class ObjectToObjectConverter implements ConditionalGenericConverter {
method = ClassUtils.getStaticMethod(targetClass, "from", sourceClass);
}
}
return method;
return (method != null && areRelatedTypes(targetClass, method.getReturnType()) ? method : null);
}
/**
* Determine if the two types reside in the same type hierarchy (i.e., type 1
* is assignable to type 2 or vice versa).
* @since 5.3.21
* @see ClassUtils#isAssignable(Class, Class)
*/
private static boolean areRelatedTypes(Class<?> type1, Class<?> type2) {
return (ClassUtils.isAssignable(type1, type2) || ClassUtils.isAssignable(type2, type1));
}
@Nullable
@@ -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.
@@ -26,7 +26,7 @@ import org.springframework.util.StringUtils;
* Converts from a String to a {@link java.util.Locale}.
*
* <p>Accepts the classic {@link Locale} String format ({@link Locale#toString()})
* as well as BCP 47 language tags ({@link Locale#forLanguageTag} on Java 7+).
* as well as BCP 47 language tags ({@link Locale#forLanguageTag}.
*
* @author Keith Donald
* @author Juergen Hoeller
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -299,7 +299,7 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment {
public void setActiveProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Activating profiles " + Arrays.asList(profiles));
logger.debug("Activating profiles " + Arrays.toString(profiles));
}
synchronized (this.activeProfiles) {
this.activeProfiles.clear();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -182,8 +182,7 @@ public abstract class AbstractFileResolvingResource extends AbstractResource {
}
/**
* This implementation returns a File reference for the given URI-identified
* resource, provided that it refers to a file in the file system.
* Determine whether the given {@link URI} represents a file in a file system.
* @since 5.0
* @see #getFile(URI)
*/
@@ -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.
@@ -50,7 +50,7 @@ public abstract class AbstractResource implements Resource {
/**
* This implementation checks whether a File can be opened,
* falling back to whether an InputStream can be opened.
* This will cover both directories and content resources.
* <p>This will cover both directories and content resources.
*/
@Override
public boolean exists() {
@@ -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.
@@ -86,7 +86,7 @@ public interface Resource extends InputStreamSource {
/**
* Determine whether this resource represents a file in a file system.
* A value of {@code true} strongly suggests (but does not guarantee)
* <p>A value of {@code true} strongly suggests (but does not guarantee)
* that a {@link #getFile()} call will succeed.
* <p>This is conservatively {@code false} by default.
* @since 5.0
@@ -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-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.
@@ -60,6 +60,18 @@ public class UrlResource extends AbstractFileResolvingResource {
private volatile URL cleanedUrl;
/**
* Create a new {@code UrlResource} based on the given URL object.
* @param url a URL
* @see #UrlResource(URI)
* @see #UrlResource(String)
*/
public UrlResource(URL url) {
Assert.notNull(url, "URL must not be null");
this.uri = null;
this.url = url;
}
/**
* Create a new {@code UrlResource} based on the given URI object.
* @param uri a URI
@@ -72,16 +84,6 @@ public class UrlResource extends AbstractFileResolvingResource {
this.url = uri.toURL();
}
/**
* Create a new {@code UrlResource} based on the given URL object.
* @param url a URL
*/
public UrlResource(URL url) {
Assert.notNull(url, "URL must not be null");
this.uri = null;
this.url = url;
}
/**
* Create a new {@code UrlResource} based on a URL path.
* <p>Note: The given path needs to be pre-encoded if necessary.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 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.
@@ -36,15 +36,16 @@ import org.springframework.core.io.ResourceLoader;
* {@link ResourceArrayPropertyEditor} for populating {@code Resource} array bean
* properties.
*
* <p>Can be used with any sort of location pattern (e.g. "/WEB-INF/*-context.xml"):
* Input patterns have to match the strategy implementation. This interface just
* specifies the conversion method rather than a specific pattern format.
* <p>Can be used with any sort of location pattern &mdash; for example,
* {@code "/WEB-INF/*-context.xml"}. However, input patterns have to match the
* strategy implementation. This interface just specifies the conversion method
* rather than a specific pattern format.
*
* <p>This interface also suggests a new resource prefix "classpath*:" for all
* matching resources from the class path. Note that the resource location is
* expected to be a path without placeholders in this case (e.g. "/beans.xml");
* JAR files or different directories in the class path can contain multiple files
* of the same name.
* <p>This interface also defines a {@code "classpath*:"} resource prefix for all
* matching resources from the class path. Note that the resource location may
* also contain placeholders &mdash; for example {@code "/beans-*.xml"}. JAR files
* or different directories in the class path can contain multiple files of the
* same name.
*
* @author Juergen Hoeller
* @since 1.0.2
@@ -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.
@@ -22,6 +22,7 @@ import java.util.function.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.NoOpLog;
/**
* Implementation of {@link Log} that wraps a list of loggers and delegates
* to the first one for which logging is enabled at the given level.
@@ -35,35 +36,114 @@ final class CompositeLog implements Log {
private static final Log NO_OP_LOG = new NoOpLog();
private final Log fatalLogger;
private final Log errorLogger;
private final Log warnLogger;
private final Log infoLogger;
private final Log debugLogger;
private final Log traceLogger;
private final List<Log> loggers;
/**
* Constructor with list of loggers. For optimal performance, the constructor
* checks and remembers which logger is on for each log category.
* Package-private constructor with list of loggers.
* @param loggers the loggers to use
*/
public CompositeLog(List<Log> loggers) {
this.fatalLogger = initLogger(loggers, Log::isFatalEnabled);
this.errorLogger = initLogger(loggers, Log::isErrorEnabled);
this.warnLogger = initLogger(loggers, Log::isWarnEnabled);
this.infoLogger = initLogger(loggers, Log::isInfoEnabled);
this.debugLogger = initLogger(loggers, Log::isDebugEnabled);
this.traceLogger = initLogger(loggers, Log::isTraceEnabled);
CompositeLog(List<Log> loggers) {
this.loggers = loggers;
}
private static Log initLogger(List<Log> loggers, Predicate<Log> predicate) {
for (Log logger : loggers) {
@Override
public boolean isFatalEnabled() {
return isEnabled(Log::isFatalEnabled);
}
@Override
public boolean isErrorEnabled() {
return isEnabled(Log::isErrorEnabled);
}
@Override
public boolean isWarnEnabled() {
return isEnabled(Log::isWarnEnabled);
}
@Override
public boolean isInfoEnabled() {
return isEnabled(Log::isInfoEnabled);
}
@Override
public boolean isDebugEnabled() {
return isEnabled(Log::isDebugEnabled);
}
@Override
public boolean isTraceEnabled() {
return isEnabled(Log::isTraceEnabled);
}
private boolean isEnabled(Predicate<Log> predicate) {
return (getLogger(predicate) != NO_OP_LOG);
}
@Override
public void fatal(Object message) {
getLogger(Log::isFatalEnabled).fatal(message);
}
@Override
public void fatal(Object message, Throwable ex) {
getLogger(Log::isFatalEnabled).fatal(message, ex);
}
@Override
public void error(Object message) {
getLogger(Log::isErrorEnabled).error(message);
}
@Override
public void error(Object message, Throwable ex) {
getLogger(Log::isErrorEnabled).error(message, ex);
}
@Override
public void warn(Object message) {
getLogger(Log::isWarnEnabled).warn(message);
}
@Override
public void warn(Object message, Throwable ex) {
getLogger(Log::isWarnEnabled).warn(message, ex);
}
@Override
public void info(Object message) {
getLogger(Log::isInfoEnabled).info(message);
}
@Override
public void info(Object message, Throwable ex) {
getLogger(Log::isInfoEnabled).info(message, ex);
}
@Override
public void debug(Object message) {
getLogger(Log::isDebugEnabled).debug(message);
}
@Override
public void debug(Object message, Throwable ex) {
getLogger(Log::isDebugEnabled).debug(message, ex);
}
@Override
public void trace(Object message) {
getLogger(Log::isTraceEnabled).trace(message);
}
@Override
public void trace(Object message, Throwable ex) {
getLogger(Log::isTraceEnabled).trace(message, ex);
}
private Log getLogger(Predicate<Log> predicate) {
for (Log logger : this.loggers) {
if (predicate.test(logger)) {
return logger;
}
@@ -71,95 +151,4 @@ final class CompositeLog implements Log {
return NO_OP_LOG;
}
@Override
public boolean isFatalEnabled() {
return (this.fatalLogger != NO_OP_LOG);
}
@Override
public boolean isErrorEnabled() {
return (this.errorLogger != NO_OP_LOG);
}
@Override
public boolean isWarnEnabled() {
return (this.warnLogger != NO_OP_LOG);
}
@Override
public boolean isInfoEnabled() {
return (this.infoLogger != NO_OP_LOG);
}
@Override
public boolean isDebugEnabled() {
return (this.debugLogger != NO_OP_LOG);
}
@Override
public boolean isTraceEnabled() {
return (this.traceLogger != NO_OP_LOG);
}
@Override
public void fatal(Object message) {
this.fatalLogger.fatal(message);
}
@Override
public void fatal(Object message, Throwable ex) {
this.fatalLogger.fatal(message, ex);
}
@Override
public void error(Object message) {
this.errorLogger.error(message);
}
@Override
public void error(Object message, Throwable ex) {
this.errorLogger.error(message, ex);
}
@Override
public void warn(Object message) {
this.warnLogger.warn(message);
}
@Override
public void warn(Object message, Throwable ex) {
this.warnLogger.warn(message, ex);
}
@Override
public void info(Object message) {
this.infoLogger.info(message);
}
@Override
public void info(Object message, Throwable ex) {
this.infoLogger.info(message, ex);
}
@Override
public void debug(Object message) {
this.debugLogger.debug(message);
}
@Override
public void debug(Object message, Throwable ex) {
this.debugLogger.debug(message, ex);
}
@Override
public void trace(Object message) {
this.traceLogger.trace(message);
}
@Override
public void trace(Object message, Throwable ex) {
this.traceLogger.trace(message, ex);
}
}
@@ -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.
@@ -35,8 +35,8 @@ import java.util.Properties;
* <p>Loading from and storing to a stream delegates to {@code Properties.load}
* and {@code Properties.store}, respectively, to be fully compatible with
* the Unicode conversion as implemented by the JDK Properties class. As of JDK 6,
* {@code Properties.load/store} will also be used for readers/writers,
* effectively turning this class into a plain backwards compatibility adapter.
* {@code Properties.load/store} is also used for readers/writers, effectively
* turning this class into a plain backwards compatibility adapter.
*
* <p>The persistence code that works with Reader/Writer follows the JDK's parsing
* strategy but does not implement Unicode conversion, because the Reader/Writer
@@ -67,18 +67,20 @@ public abstract class MimeTypeUtils {
/**
* Public constant mime type for {@code application/graphql+json}.
* @since 5.3.19
* @see <a href="https://github.com/graphql/graphql-over-http">GraphQL over HTTP spec</a>
* */
*/
public static final MimeType APPLICATION_GRAPHQL;
/**
* A String equivalent of {@link MimeTypeUtils#APPLICATION_GRAPHQL}.
* @since 5.3.19
*/
public static final String APPLICATION_GRAPHQL_VALUE = "application/graphql+json";
/**
* Public constant mime type for {@code application/json}.
* */
*/
public static final MimeType APPLICATION_JSON;
/**
@@ -804,11 +804,11 @@ public abstract class StringUtils {
/**
* Parse the given {@code String} value into a {@link Locale}, accepting
* the {@link Locale#toString} format as well as BCP 47 language tags.
* the {@link Locale#toString} format as well as BCP 47 language tags as
* specified by {@link Locale#forLanguageTag}.
* @param localeValue the locale value: following either {@code Locale's}
* {@code toString()} format ("en", "en_UK", etc), also accepting spaces as
* separators (as an alternative to underscores), or BCP 47 (e.g. "en-UK")
* as specified by {@link Locale#forLanguageTag} on Java 7+
* @return a corresponding {@code Locale} instance, or {@code null} if none
* @throws IllegalArgumentException in case of an invalid locale specification
* @since 5.0.4
@@ -1,6 +1,6 @@
/**
* Miscellaneous utility classes, such as String manipulation utilities,
* a Log4J configurer, and a state holder for paged lists of objects.
* Miscellaneous utility classes, such as utilities for working with strings,
* classes, collections, reflection, etc.
*/
@NonNullApi
@NonNullFields
@@ -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.
@@ -52,11 +52,6 @@ import org.springframework.util.StringUtils;
@SuppressWarnings("serial")
public final class DataSize implements Comparable<DataSize>, Serializable {
/**
* The pattern for parsing.
*/
private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");
/**
* Bytes per Kilobyte.
*/
@@ -179,9 +174,9 @@ public final class DataSize implements Comparable<DataSize>, Serializable {
public static DataSize parse(CharSequence text, @Nullable DataUnit defaultUnit) {
Assert.notNull(text, "Text must not be null");
try {
Matcher matcher = PATTERN.matcher(text);
Matcher matcher = DataSizeUtils.PATTERN.matcher(text);
Assert.state(matcher.matches(), "Does not match data size pattern");
DataUnit unit = determineDataUnit(matcher.group(2), defaultUnit);
DataUnit unit = DataSizeUtils.determineDataUnit(matcher.group(2), defaultUnit);
long amount = Long.parseLong(matcher.group(1));
return DataSize.of(amount, unit);
}
@@ -190,11 +185,6 @@ public final class DataSize implements Comparable<DataSize>, Serializable {
}
}
private static DataUnit determineDataUnit(String suffix, @Nullable DataUnit defaultUnit) {
DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
return (StringUtils.hasLength(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}
/**
* Checks if this size is negative, excluding zero.
* @return true if this size has a size less than zero bytes
@@ -271,4 +261,23 @@ public final class DataSize implements Comparable<DataSize>, Serializable {
return Long.hashCode(this.bytes);
}
/**
* Static nested class to support lazy loading of the {@link #PATTERN}.
* @since 5.3.21
*/
private static class DataSizeUtils {
/**
* The pattern for parsing.
*/
private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");
private static DataUnit determineDataUnit(String suffix, @Nullable DataUnit defaultUnit) {
DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
return (StringUtils.hasLength(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}
}
}
@@ -824,6 +824,9 @@ class DefaultConversionServiceTests {
assertThat(ISBN.toStringCount).as("toString() invocations").isEqualTo(1);
}
/**
* @see org.springframework.core.convert.support.ObjectToObjectConverterTests
*/
@Test
void convertObjectToObjectUsingValueOfMethod() {
ISBN.reset();
@@ -0,0 +1,123 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.convert.support;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.ConverterNotFoundException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for {@link ObjectToObjectConverter}.
*
* @author Sam Brannen
* @author Phil Webb
* @since 5.3.21
* @see org.springframework.core.convert.converter.DefaultConversionServiceTests#convertObjectToObjectUsingValueOfMethod()
*/
class ObjectToObjectConverterTests {
private final GenericConversionService conversionService = new GenericConversionService() {{
addConverter(new ObjectToObjectConverter());
}};
/**
* This test effectively verifies that the {@link ObjectToObjectConverter}
* was properly registered with the {@link GenericConversionService}.
*/
@Test
void nonStaticToTargetTypeSimpleNameMethodWithMatchingReturnType() {
assertThat(conversionService.canConvert(Source.class, Data.class))
.as("can convert Source to Data").isTrue();
Data data = conversionService.convert(new Source("test"), Data.class);
assertThat(data).asString().isEqualTo("test");
}
@Test
void nonStaticToTargetTypeSimpleNameMethodWithDifferentReturnType() {
assertThat(conversionService.canConvert(Text.class, Data.class))
.as("can convert Text to Data").isFalse();
assertThat(conversionService.canConvert(Text.class, Optional.class))
.as("can convert Text to Optional").isFalse();
assertThatExceptionOfType(ConverterNotFoundException.class)
.as("convert Text to Data")
.isThrownBy(() -> conversionService.convert(new Text("test"), Data.class));
}
@Test
void staticValueOfFactoryMethodWithDifferentReturnType() {
assertThat(conversionService.canConvert(String.class, Data.class))
.as("can convert String to Data").isFalse();
assertThatExceptionOfType(ConverterNotFoundException.class)
.as("convert String to Data")
.isThrownBy(() -> conversionService.convert("test", Data.class));
}
static class Source {
private final String value;
private Source(String value) {
this.value = value;
}
public Data toData() {
return new Data(this.value);
}
}
static class Text {
private final String value;
private Text(String value) {
this.value = value;
}
public Optional<Data> toData() {
return Optional.of(new Data(this.value));
}
}
static class Data {
private final String value;
private Data(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
public static Optional<Data> valueOf(String string) {
return (string != null) ? Optional.of(new Data(string)) : Optional.empty();
}
}
}
@@ -25,6 +25,7 @@ import java.util.Arrays;
import org.springframework.core.testfixture.io.buffer.AbstractDataBufferAllocatingTests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -83,8 +84,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
DataBuffer buffer = createDataBuffer(1);
try {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.readPosition(-1));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.readPosition(-1));
}
finally {
release(buffer);
@@ -97,8 +97,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
DataBuffer buffer = createDataBuffer(1);
try {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.readPosition(1));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.readPosition(1));
}
finally {
release(buffer);
@@ -113,8 +112,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
try {
buffer.write((byte) 'a');
buffer.read();
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.writePosition(0));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.writePosition(0));
}
finally {
release(buffer);
@@ -127,8 +125,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
DataBuffer buffer = createDataBuffer(1);
try {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.writePosition(2));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.writePosition(2));
}
finally {
release(buffer);
@@ -641,8 +638,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
DataBuffer slice = buffer.slice(1, 2);
assertThat(slice.readableByteCount()).isEqualTo(2);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
assertThatException().isThrownBy(() -> slice.write((byte) 0));
buffer.write((byte) 'c');
assertThat(buffer.readableByteCount()).isEqualTo(3);
@@ -670,8 +666,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
DataBuffer slice = buffer.retainedSlice(1, 2);
assertThat(slice.readableByteCount()).isEqualTo(2);
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
slice.write((byte) 0));
assertThatException().isThrownBy(() -> slice.write((byte) 0));
buffer.write((byte) 'c');
assertThat(buffer.readableByteCount()).isEqualTo(3);
@@ -734,11 +729,8 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
assertThat(buffer.getByte(0)).isEqualTo((byte) 'a');
assertThat(buffer.getByte(1)).isEqualTo((byte) 'b');
assertThat(buffer.getByte(2)).isEqualTo((byte) 'c');
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.getByte(-1));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() ->
buffer.getByte(3));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.getByte(-1));
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> buffer.getByte(3));
release(buffer);
}
@@ -0,0 +1,86 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.log;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.when;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit tests for {@link CompositeLog}.
* @author Rossen Stoyanchev
*/
public class CompositeLogTests {
private final Log logger1 = mock(Log.class);
private final Log logger2 = mock(Log.class);
private final CompositeLog compositeLog = new CompositeLog(Arrays.asList(logger1, logger2));
@Test
void useFirstLogger() {
when(logger1.isInfoEnabled()).thenReturn(true);
when(logger2.isInfoEnabled()).thenReturn(true);
this.compositeLog.info("info message");
verify(this.logger1).isInfoEnabled();
verify(this.logger1).info("info message");
verifyNoMoreInteractions(this.logger1);
verifyNoMoreInteractions(this.logger2);
}
@Test
void useSecondLogger() {
when(logger1.isInfoEnabled()).thenReturn(false);
when(logger2.isInfoEnabled()).thenReturn(true);
this.compositeLog.info("info message");
verify(this.logger1).isInfoEnabled();
verify(this.logger2).isInfoEnabled();
verify(this.logger2).info("info message");
verifyNoMoreInteractions(this.logger1);
verifyNoMoreInteractions(this.logger2);
}
@Test
void useNeitherLogger() {
when(logger1.isInfoEnabled()).thenReturn(false);
when(logger2.isInfoEnabled()).thenReturn(false);
this.compositeLog.info("info message");
verify(this.logger1).isInfoEnabled();
verify(this.logger2).isInfoEnabled();
verifyNoMoreInteractions(this.logger1);
verifyNoMoreInteractions(this.logger2);
}
}
@@ -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.
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -27,45 +28,33 @@ import static org.assertj.core.api.Assertions.assertThat;
* Test construction of arrays.
*
* @author Andy Clement
* @author Sam Brannen
*/
public class ArrayConstructorTests extends AbstractExpressionTests {
class ArrayConstructorTests extends AbstractExpressionTests {
@Test
public void simpleArrayWithInitializer() {
evaluateArrayBuildingExpression("new int[]{1,2,3}", "[1,2,3]");
evaluateArrayBuildingExpression("new int[]{}", "[]");
evaluate("new int[]{}.length", "0", Integer.class);
}
@Test
public void conversion() {
void conversion() {
evaluate("new String[]{1,2,3}[0]", "1", String.class);
evaluate("new int[]{'123'}[0]", 123, Integer.class);
}
@Test
public void multidimensionalArrays() {
evaluateAndCheckError("new int[][]{{1,2},{3,4}}", SpelMessage.MULTIDIM_ARRAY_INITIALIZER_NOT_SUPPORTED);
evaluateAndCheckError("new int[3][]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new int[]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new String[]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new int[][1]", SpelMessage.MISSING_ARRAY_DIMENSION);
void primitiveTypeArrayConstructors() {
evaluateArrayBuildingExpression("new int[]{}", "{}");
evaluateArrayBuildingExpression("new int[]{1,2,3,4}", "{1, 2, 3, 4}");
evaluateArrayBuildingExpression("new boolean[]{true,false,true}", "{true, false, true}");
evaluateArrayBuildingExpression("new char[]{'a','b','c'}", "{'a', 'b', 'c'}");
evaluateArrayBuildingExpression("new long[]{1,2,3,4,5}", "{1, 2, 3, 4, 5}");
evaluateArrayBuildingExpression("new short[]{2,3,4,5,6}", "{2, 3, 4, 5, 6}");
evaluateArrayBuildingExpression("new double[]{1d,2d,3d,4d}", "{1.0, 2.0, 3.0, 4.0}");
evaluateArrayBuildingExpression("new float[]{1f,2f,3f,4f}", "{1.0, 2.0, 3.0, 4.0}");
evaluateArrayBuildingExpression("new byte[]{1,2,3,4}", "{1, 2, 3, 4}");
evaluate("new int[]{}.length", "0", Integer.class);
}
@Test
public void primitiveTypeArrayConstructors() {
evaluateArrayBuildingExpression("new int[]{1,2,3,4}", "[1,2,3,4]");
evaluateArrayBuildingExpression("new boolean[]{true,false,true}", "[true,false,true]");
evaluateArrayBuildingExpression("new char[]{'a','b','c'}", "[a,b,c]");
evaluateArrayBuildingExpression("new long[]{1,2,3,4,5}", "[1,2,3,4,5]");
evaluateArrayBuildingExpression("new short[]{2,3,4,5,6}", "[2,3,4,5,6]");
evaluateArrayBuildingExpression("new double[]{1d,2d,3d,4d}", "[1.0,2.0,3.0,4.0]");
evaluateArrayBuildingExpression("new float[]{1f,2f,3f,4f}", "[1.0,2.0,3.0,4.0]");
evaluateArrayBuildingExpression("new byte[]{1,2,3,4}", "[1,2,3,4]");
}
@Test
public void primitiveTypeArrayConstructorsElements() {
void primitiveTypeArrayConstructorsElements() {
evaluate("new int[]{1,2,3,4}[0]", 1, Integer.class);
evaluate("new boolean[]{true,false,true}[0]", true, Boolean.class);
evaluate("new char[]{'a','b','c'}[0]", 'a', Character.class);
@@ -78,15 +67,34 @@ public class ArrayConstructorTests extends AbstractExpressionTests {
}
@Test
public void errorCases() {
void errorCases() {
evaluateAndCheckError("new int[]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new String[]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new int[3][]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new int[][1]", SpelMessage.MISSING_ARRAY_DIMENSION);
evaluateAndCheckError("new char[7]{'a','c','d','e'}", SpelMessage.INITIALIZER_LENGTH_INCORRECT);
evaluateAndCheckError("new char[3]{'a','c','d','e'}", SpelMessage.INITIALIZER_LENGTH_INCORRECT);
evaluateAndCheckError("new int[][]{{1,2},{3,4}}", SpelMessage.MULTIDIM_ARRAY_INITIALIZER_NOT_SUPPORTED);
evaluateAndCheckError("new char[2]{'hello','world'}", SpelMessage.TYPE_CONVERSION_ERROR);
// Could conceivably be a SpelMessage.INCORRECT_ELEMENT_TYPE_FOR_ARRAY, but it appears
// that SpelMessage.INCORRECT_ELEMENT_TYPE_FOR_ARRAY is not actually (no longer?) used
// in the code base.
evaluateAndCheckError("new Integer[3]{'3','ghi','5'}", SpelMessage.TYPE_CONVERSION_ERROR);
evaluateAndCheckError("new String('a','c','d')", SpelMessage.CONSTRUCTOR_INVOCATION_PROBLEM);
// Root cause: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
evaluateAndCheckError("new java.util.ArrayList(T(java.lang.Integer).MAX_VALUE)", SpelMessage.CONSTRUCTOR_INVOCATION_PROBLEM);
int threshold = 256 * 1024; // ConstructorReference.MAX_ARRAY_ELEMENTS
evaluateAndCheckError("new int[T(java.lang.Integer).MAX_VALUE]", SpelMessage.MAX_ARRAY_ELEMENTS_THRESHOLD_EXCEEDED, 0, threshold);
evaluateAndCheckError("new int[1024 * 1024][1024 * 1024]", SpelMessage.MAX_ARRAY_ELEMENTS_THRESHOLD_EXCEEDED, 0, threshold);
}
@Test
public void typeArrayConstructors() {
void typeArrayConstructors() {
evaluate("new String[]{'a','b','c','d'}[1]", "b", String.class);
evaluateAndCheckError("new String[]{'a','b','c','d'}.size()", SpelMessage.METHOD_NOT_FOUND, 30, "size()",
"java.lang.String[]");
@@ -94,113 +102,25 @@ public class ArrayConstructorTests extends AbstractExpressionTests {
}
@Test
public void basicArray() {
void basicArray() {
evaluate("new String[3]", "java.lang.String[3]{null,null,null}", String[].class);
}
@Test
public void multiDimensionalArray() {
void multiDimensionalArrays() {
evaluate("new String[2][2]", "[Ljava.lang.String;[2]{[2]{null,null},[2]{null,null}}", String[][].class);
evaluate("new String[3][2][1]",
"[[Ljava.lang.String;[3]{[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}}}",
String[][][].class);
}
@Test
public void constructorInvocation03() {
evaluateAndCheckError("new String[]", SpelMessage.MISSING_ARRAY_DIMENSION);
}
public void constructorInvocation04() {
evaluateAndCheckError("new Integer[3]{'3','ghi','5'}", SpelMessage.INCORRECT_ELEMENT_TYPE_FOR_ARRAY, 4);
}
private String evaluateArrayBuildingExpression(String expression, String expectedToString) {
private void evaluateArrayBuildingExpression(String expression, String expectedToString) {
SpelExpressionParser parser = new SpelExpressionParser();
Expression e = parser.parseExpression(expression);
Object o = e.getValue();
assertThat(o).isNotNull();
assertThat(o.getClass().isArray()).isTrue();
StringBuilder s = new StringBuilder();
s.append('[');
if (o instanceof int[]) {
int[] array = (int[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof boolean[]) {
boolean[] array = (boolean[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof char[]) {
char[] array = (char[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof long[]) {
long[] array = (long[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof short[]) {
short[] array = (short[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof double[]) {
double[] array = (double[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof float[]) {
float[] array = (float[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else if (o instanceof byte[]) {
byte[] array = (byte[]) o;
for (int i = 0; i < array.length; i++) {
if (i > 0) {
s.append(',');
}
s.append(array[i]);
}
}
else {
throw new IllegalStateException("Not supported " + o.getClass());
}
s.append(']');
assertThat(s.toString()).isEqualTo(expectedToString);
return s.toString();
Object array = e.getValue();
assertThat(array).isNotNull();
assertThat(array.getClass().isArray()).isTrue();
assertThat(ObjectUtils.nullSafeToString(array)).isEqualTo(expectedToString);
}
}

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