Supporting ScriptEngine#eval(String, Bindings) when no render function
is specified allows to support use cases where script templates are
simply evaluating a script expression with an even more simplified
configuration.
This improvement also makes it possible to use script engines that
do not implement Invocable.
Issue: SPR-15115
This commit also removes nullability from two common spots: ResolvableType.getType() and TargetSource.getTarget(), both of which are never effectively null with any regular implementation. For such scenarios, a non-null empty type/target is the cleaner contract.
Issue: SPR-15540
Beyond just formally declaring the current behavior, this revision actually enforces non-null behavior in selected signatures now, not tolerating null values anymore when not explicitly documented. It also changes some utility methods with historic null-in/null-out tolerance towards enforced non-null return values, making them a proper citizen in non-null assignments.
Some issues are left as to-do: in particular a thorough revision of spring-test, and a few tests with unclear failures (ignored as "TODO: NULLABLE") to be sorted out in a follow-up commit.
Issue: SPR-15540
With the new `ParsingPathMatcher` implementation, new patterns are now
allowed, such as `"/foo/{*bar}". The `"{*bar}"` segment will capture
everything until the end of the given path. Adding other elements after
that segment is illegal and will throw exceptions.
One can configure on a `PathMatchConfigurer` various options like
`useTrailingSlashMatch` and `useSuffixPatternMatch`; those options, when
enabled, will try to append suffixes like `".*"` and `"/"` to existing
path patterns. In case of a "capture the rest" pattern segment, those
options won't be honored.
This is why this commit ensures that an exception is thrown at the start
of the application if an illegal configuration is applied to the
`PathMatchConfigurer`.
Issue: SPR-15303, SPR-15558
This commit introduces 2 new @Nullable and @NonNullApi
annotations that leverage JSR 305 (dormant but available via
Findbugs jsr305 dependency and already used by libraries
like OkHttp) meta-annotations to specify explicitly
null-safety of Spring Framework parameters and return values.
In order to avoid adding too much annotations, the
default is set at package level with @NonNullApi and
@Nullable annotations are added when needed at parameter or
return value level. These annotations are intended to be used
on Spring Framework itself but also by other Spring projects.
@Nullable annotations have been introduced based on Javadoc
and search of patterns like "return null;". It is expected that
nullability of Spring Framework API will be polished with
complementary commits.
In practice, this will make the whole Spring Framework API
null-safe for Kotlin projects (when KT-10942 will be fixed)
since Kotlin will be able to leverage these annotations to
know if a parameter or a return value is nullable or not. But
this is also useful for Java developers as well since IntelliJ
IDEA, for example, also understands these annotations to
generate warnings when unsafe nullable usages are detected.
Issue: SPR-15540
Prior to this commit, resolving resources from webjars using the
`WebJarAssetLocator.getFullPath` could lead to multiple candidates,
since this method is trying to find *any* resource matching that path
under the given webjar location.
This commit replaces that call with
`WebJarAssetLocator.getFullPathExact`, which avoids those multiple
matches and only resolves resources if the given path is exact.
Issue: SPR-15526
(cherry picked from commit e2aa117ff9)
Prior to this commit, the AbstractFlashMapManager has used the
originating URI but the query string of the forwarded request. That
resulted to FlashMap not being matched even when both originating
URI and query string matched the FlashMap attributes. The originating
query string is now used to match the forwarded request.
Issue: SPR-15505
HttpMessageConverter's are client and server and arguably shouldn't
contain a server-side concept such a response status.
The status field is recent, it was added to differentiate 400 vs 500
errors with Jackson 2.9+ but there is no need for it since the same
distinction is reflected in raising an HttpMessageNotReadableException
vs a general HttpMessageConversionException.
Issue: SPR-15516
Spring MVC now treats Flux<String> + "application/json" as (serialized)
text to be written directly to the response as is. This is consistent
with the rendering of String + "application/json".
Issue: SPR-15456
InvalidDefinitionException has been introduced in Jackson 2.9 to be
able to differentiate invalid data sent from the client (should still
generate a 4xx HTTP status code) from server side errors like beans with
no default constructor (should generate a 5xx HTTP status code).
Issue: SPR-14925
This commit adds support for reactive library types to be returned
directly from controller methods adapting them either to a
ResponseBodyEmitter (streaming) or DeferredResult (non-streaming).
The reactive libraries supported are the ones that can adapted to a
Reactive Streams Publisher through the ReactiveAdapterRegistry.
Issue: SPR-15365
Revise Javadoc on AsyncHandlerMethodReturnValueHandler to clarify its
main purpose is to prioritze custom async return value handlers ahead
of built-in ones. Also replace the interface from built-in handlers
which are prioritized already.
Remove DeferredResultAdapter and ResponseBodyEmitterAdapter --
introduced in 4.3 for custom async return value handling, since for
5.0 we will add built-in support for reactive types and the value of
these contracts becomes very marginal.
Issue: SPR-15365
This commit changes `ResourceTransformerSupport` to look for the
`ResourceUrlProvider` in the current request if none is configured on
the resource transformer itself.
Issue: SPR-15369
Prior to this commit, the `VersionResourceResolver` implementations of
`resolveUrlPathInternal` would delegate to the resolver chain but would
never use the give result if the current request didn't match a
configured version strategy pattern.
This is a problem if the resolver supposed to resolve the resource path
is configured after a `VersionResourceResolver` in the resolver chain;
this means that other resolver never gets to participate in the result
of the chain.
Issue: SPR-15372
Includes a new overloaded ModelAndView constructor with an HttpStatus argument, as well as a HandlerMethodArgumentResolverSupport refactoring (revised checkParameterType signature, actually implementing the HandlerMethodArgumentResolver interface).
Issue: SPR-15199
This commit introduces a `useRegisteredExtensionsOnly` property that
indicates whether classes that use the `MediaTypeFactory` for supplying
default media types can do so.
- In classes that were introduced in Spring 5.0, the
`useRegisteredExtensionsOnly` property takes the place of the
`useJaf` property that was removed in 0aaa652
- In classes that existed before Spring 5.0, the
`useRegisteredExtensionsOnly` property is added in addition to the
deprecated `useJaf`, the latter delegating to the former, but with
flipped behavior.
Issue: SPR-14908
This commit changes the `MockServletContext.getMimeType` method to use
`MediaTypeFactory` instead of JAF. It also adds a `addMimeType(String,
MediaType)` method to customize the mime types returned from said
method.
Issue: SPR-14908
This commit updates the main code base to conform to the dropped JAF
dependency in MediaTypeFactory. Specifically, it
- Removes JAF detection (JAF_PRESENT constants)
- Deprecated useJaf properties, with no direct replacement.
- Updated docs to remove JAF references, in favor of MediaTypeFactory.
Issue: SPR-14908
This commit introduces a PathPatternParser which parses request pattern
strings into PathPattern objects which can then be used to fast
match incoming string paths. The parser and matching supports the syntax
as described in SPR-14544. The code is optimized around the common usages
of request patterns and is designed to create very little transient
garbage when matching.
Issue: SPR-14544
Codacy warns us that there are several references to Boolean
constructors in the tests. Direct usage of the Boolean constructor is
discouraged and even deprecated in Java 9 [1]. Boolean constructor use
can easily be replaced with the constant instances.
This commit contains the following changes:
- replace references to Boolean constructors with boolean constants in
JSP tag tests
- update the copyright year where necessary
- BooleanComparatorTests is intentionally left unchanged as it should
also work with the non-constant instances correctly
[1] http://download.java.net/java/jdk9/docs/api/java/lang/Boolean.html#Boolean-boolean-
Issue: SPR-15076
Kotlin JSR 223 support currently requires kotlin-script-util
dependency (jcabi-aether, maven-core and aether-api can be
excluded since they are only used for live import of
dependencies and bring a lot of JARs in the classpath) and a
/META-INF/services/javax.script.ScriptEngineFactory
file specifying the ScriptEngineFactory to use, in that case
org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory.
Issue: SPR-15059
ServerWebExchange now provides access to "requestParams" as a
MulitValueMap with query parameters and form data combined.
The combined map is then used for the params condition of
@RequestMapping purposes () and also for @RequestParam arguments.
Issue: SPR-15000
When getting the lookup path of a resource, both query params and hashes
should be removed from the request path.
This commit fixes the public path resolution for paths like
`/resources/main.svg#icon-hamburgermenu`.
Issue: SPR-14928
Prior to this commit, `@ExceptionHandler` methods could not be injected
with `RedirectAttributes` arguments. This would make it impossible to
handle an error by redirecting to another view and add flashmap
attributes, to be included in the model when the next view is called.
Here is an example:
```
@ExceptionHandler(MyException.class)
public String handleException(MyException ex, RedirectAttributes
redirectAttributes) {
redirectAttributes.addFlashAttribute("errorMessage",
"This is an error message");
return "redirect:/";
}
```
This commit adds a new `RedirectAttributesMethodArgumentResolver`
instance in the list of pre-configured `HandlerMethodArgumentResolver`
in `ExceptionHandlerExceptionResolver`.
Issue: SPR-14651
This commit polishes Kotlin nullable support by reusing
MethodParameter#isOptional() instead of adding a new
MethodParameter#isNullable() method, adds
Kotlin tests and introduces Spring Web Reactive
support.
Issue: SPR-14165
Where `isOptional` is used, also check for `isNullable` i.e.
values are not considered required if they are Kotlin nullables:
- spring-messaging: named value method arguments
- spring-web: named value method arguments
- spring-webmvc: request parts
This means that Kotlin client code no longer has to explicity specify
"required=false" for Kotlin nullables -- this information is inferred
automatically by the framework.
Issue: SPR-14165
In case the filter is also registered to the ERROR dispatcher, the
following happens:
* the filter is executed once for the regular execution
* the filter should be executed a second time when dispatched to error
Since the filter is a `OncePerRequestFilter`, the filter is only
executed once and won't be executed when handling the error.
This can lead to situations like spring-projects/spring-boot#7348
This commit makes this filter a simple `GenericFilterBean`.
Issue: SPR-14891
When resolved through the `GzipResourceResolver`, CSS files can be
resolved as their pre-gzipped variant, if a ".gz" file is present in the
configured resource locations.
Such resources are gzipped and thus should not be transformed by
`CssLinkResourceTransformer`s, since rewriting those would need to
uncompress/transform/recompress. This would lead to poorer performances
than resolving plain resources and delegating compression to the
container.
This commit checks for `GzippedResource` instances in
`CssLinkResourceTransformer` and avoids processing them.
Issue: SPR-14773
Before this change the getHttpEntityType method in
HttpEntityMethodProcessor raised an ISE if the generic type cannot be
detected. That made sense for resolving a controller method argument
where the target body type is crucial. However for a return value
the generic type should not be required since we either have an
actual body or no body at all in which case it doesn't even matter.
This change relaxes the checks and defaults to Object.class for the
ResponseEntity generic type on the return value side.
Issue: SPR-14799
Prior to this commit, `ResourceTransformer` implementations would
resolve internal links to other resources: both relative and absolute
request paths.
For relative request paths, those transformers would call
`ResourceTransformerSupport.resolveUrlPath` with the resource path,
as provided in the original file. This can cause problems when a
`CachingResourceResolver` is configured in the resolver chain, because
this resolver is caching resources, deriving the cache key from the
given resource path — this can cause collisions for cases like this:
resources/
|--foo/
| |--foo.css (imports style.css)
| |--style.css
|--bar/
| |--bar.css (imports style.css)
| |--style.css
The first "style.css" resolved resource is then cached and will be given
to any request asking for "style.css".
To avoid those issues, this commit improves the `ResourceTransformer`
implementations to calculate the absolute request path before asking the
chain to resolve the resource URL, thus avoiding duplications.
The resource chain will be then asked to resolve "/foo/style/css" or
"/bar/style.css".
Issue: SPR-14597
Prior to this commit, the `HttpEntityMethodProcessor` would avoid
writing ETag/Last-Modified response headers before calling
`ServletWebRequest` to process conditional requests. This was done to
avoid duplicate response header values due to headers being already
written to the underlying servlet response.
This is still necessary for GET/HEAD requests, since this is properly
handled by `ServletWebRequest` for those cases. But
`HttpEntityMethodProcessor` should not make that decision for
PUT/PATCH/POST responses since developers are adding response headers on
purpose and should be in control of the situation — whereas
`ServletWebRequest` does not write those headers in those cases.
Issue: SPR-14767
This commit overrides the `checkResource` implementation in
`ScriptTemplateView` in order to check if the template file resource is
available and if the resolver can then proceed with rendering the
template.
Issue: SPR-14729
Cherry-picked from: 66b370e10
In order to simplify configuration for use cases involving @Bean where
only a bean name or aliases are supplied as an attribute, this commit
introduces a new 'value' attribute that is an @AliasFor 'name' in @Bean.
Issue: SPR-14728
Since appcache manifests can have various file extensions, developers
should register the (file extension, media type) mapping in their Spring
MVC / Reactive Web configuration.
This commit adds javadoc on both `AppCacheManifestTransformer` variants
to explain how to do that.
Issue: SPR-14510
Rather than setting the status to 503 directly from the timeout
interceptor which no longer seems to work reliably with Servlet
containers like Jetty even performing an additional ERROR dispatch back
to the original URL, we know rather set the DeferredResult to an
AsyncTimeoutException, which results in a dispatch and standard
handling within Spring MVC. This should be a more reliable way of
dealing with timeouts.
Issue: SPR-14669
This commit changes the default file extension configured with
`AppCacheManifestTranformer`. This ResourceTransformer was previously
considering `.manifest` files by default, but this has been changed in
the official spec to `appcache`, in order not to clash with Microsoft's
unregistered application/manifest type.
Issue: SPR-14687
`ResolvedResource` is a rather generic name - changing the extended
interface to something more meaningful: `HttpResource`.
For now, implementations are linked with the resource handling chain,
but this aspect has been removed from the interface documentation.
Issue: SPR-14264
Prior to this commit, the resource handling chain and its
`ResourceResolvers` would use specific `Resource` implementations in
order to add resource metadata to the HTTP response. For example,
`VersionedResource` and `EncodedResource` are both adding specific HTTP
response headers.
This commit aims at making this mechanism more stable and reusable,
since the previous implementation would fail in case a resolved resource
would be both a `VersionedResource` wrapping a `EncodedResource` (or the
other way arount). Only one of the specific implementations would
contribute its metadata since the code supporting that in
`ResourceHttpRequestHandler` would only check for `instanceof` tests,
whereas those implementations are acutally delegating calls to
the wrapped resource.
Now both `VersionedResource` and `EncodedResource` have been replaced by
specific implementations of `ResolvedResource`, which directly provides
those HTTP response headers as part of `getResponseHeaders()`.
This commit applies the same changes for the web reactive
implementations and its `ResourceWebHandler`.
Issue: SPR-14264
Since SPR-14522, the web reactive framework supports checkNotModified
features. This commit aligns the existing MVC infrastructure with
web reactive's behavior.
Because of the new Servlet 3.0 baseline, some constraints
aren't relevant anymore and duplicate code has been removed in
`HttpEntityMethodProcessor`.
Issue: SPR-14659
This commit documents the regexp support in `AntPathMatcher` when
matching for URL patterns. This support is also mentioned in places
where developers can register patterns for ViewControllers or resource
handlers.
Issue: SPR-14652
This is a follow-up on commit 3b95e0b relaxing the expectation that a
ServletContext is present. Instead we check defensively and fall back
on PathExtensionContentNegotiationStrategy which can use JAF.
Issue: SPR-14577
This commit adds Smile and CBOR Jackson HttpMessageConverters
and make it possible to create Smile and CBOR ObjectMapper via
Jackson2ObjectMapperBuilder, which now allows to specify any
custom JsonFactory.
Like with JSON and XML Jackson support, the relevant
HttpMessageConverters are automaticially configurered by
Spring MVC WebMvcConfigurationSupport if jackson-dataformat-smile
or jackson-dataformat-cbor dependencies are found in the classpath.
Issue: SPR-14435
HttpEntityMethodProcessor should not throw IllegalArgumentExceptions for
invalid If-None-Match headers.
For those cases, this commit makes sure that both
`HttpEntityMethodProcessor` and `ServletWebRequest` have a consistent
behavior and stop processing the request as conditional and leave the
handler handle it.
Issue: SPR-14559
xmlunit 2.1.0 is the latest release for xmlunit.
Most of the xmlunit functionality used within spring-framework
was done through the xmlunit 1.x helper class
`org.custommonkey.xmlunit.XMLAssert`.
As of xmlunit 2.0.0 most of the XML comparison methods are done
through hamcrest matchers exposed by the xmlunit-matchers
library. In some cases during the migration, the matchers
had to be customized with custom `NodeMatcher` or
`DifferenceEvaluator` instances in order to keep the assertions
correct (they were performed with xmlunit 1.x previously).
Issue: SPR-14043
This commit adds a test runtime dependency on log4j 2 for every project
and migrates all log4j.properties files to log4j2-test.xml files.
Issue: SPR-14431
This commit also removes the corresponding deprecated Servlet MVC variant and updates DispatcherServlet.properties to point to RequestMappingHandlerMapping/Adapter by default.
Issue: SPR-14129
Originally handleNoMatch looked for partial matches based on URL
pattern, HTTP method, consumes, produces, and params in that order
but without narrowing down the set of partial matches resulting in
potentially inaccruate response status codes
Commit 473de0 added an improvement to narrow the set with partial
matches for URL pattern and HTTP method matches.
This commit overhauls handleNoMatch so that the narrowing down of
matches happens at each stage resulting in more accurate error
reporting for request mappings with fine-grained conditions.
Issue: SPR-14397
As of 4.3 ResourceHttpRequestHandler delegates to the configured
ContentNegotiationManager, or one created internally, to look up
the media type for are resource.
This commit ensures the internally created ContentNegotiationManager is
correctly injected with the ServletContext through which it can perform
lookups as before.
Also the ServletPathContentNegotiationStrategy now checks the
ServletContext first and then delegates to its parent the
PathContentNegotiationStrategy and not vice versa. This is
consistent with how handleNoMatch (also in the same class) works
and also matches how ResourceHttpRequestHandler worked before 4.3.
Issue: SPR-14368
This commit sets the response content type to
"text/event-stream;charset=UTF-8". Even if the SSE spec says that the
encoding should always be UTF-8 and that specifying the charset is
optional, we're setting it in all cases, since some containers might use
the default encoding "ISO-8859-1" and confuse HTTP clients.
Issue: SPR-14407
This commit updates AbstractHandlerExceptionResolver to only log at the
WARN level exceptions that are actually resolved by the
ExceptionResolver.
In case developers wish to log each time an ExceptionResolver is called,
a DEBUG level log is still available.
Issue: SPR-14392
When comparing multiple matching @RequestMapping's, the HTTP method
condition has the lowest precedence. It's mainly about ensuring an
explicit mapping wins over an implicit (i.e. no method) one.
As of 4.3 HTTP HEAD is handled automatically for controller methods
that match to GET. However an explicit mapping HTTP HEAD allows an
application to take control.
This commit ensures that for HTTP HEAD requests the HTTP method
condition is checked first which means that an explicit HEAD mapping
now trumps all other conditions.
Normally we look for the most specific matching @RequestMapping.
For HTTP HEAD we now look for the most specific match among
@RequestMapping methods with a HEAD mapping first.
Issue: SPR-14383
Before this change Consumes/ProducesRequestCondition shared a common
match method in the package private AbstractMediaTypeExpression. The
benefit, two lines of code, was negligible but was forcing each
condition into parsing the content type of the request body or
evaluating the content type for the response respectively.
This change removes the shared match method and brings it down into
each sub-class resulting in a performance improvement as well as in
simpler code including exception handling.
Issue: SPR-14299