From 1f248b34f6a39e7741eb30965bc8d4cb74051b0e Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sun, 17 Oct 2021 18:49:02 +0200 Subject: [PATCH] Apply "instanceof pattern matching" in spring-webmvc This commit also applies additional clean-up tasks such as the following. - final fields - diamond operator (<>) for anonymous inner classes - try with resources - multi-catch This has only been applied to `src/main/java`. --- .../springframework/web/servlet/FlashMap.java | 5 +- .../web/servlet/FrameworkServlet.java | 35 +++++------ .../web/servlet/HandlerExecutionChain.java | 8 +-- .../AnnotationDrivenBeanDefinitionParser.java | 5 +- .../annotation/ViewControllerRegistry.java | 4 +- .../annotation/ViewResolverRegistry.java | 6 +- .../ChangePathPatternParserVisitor.java | 5 +- .../DefaultEntityResponseBuilder.java | 11 ++-- .../function/DefaultServerRequest.java | 19 +++--- .../servlet/function/RequestPredicates.java | 23 ++++---- .../handler/AbstractHandlerMapping.java | 59 +++++++++---------- ...bstractHandlerMethodExceptionResolver.java | 5 +- .../handler/AbstractHandlerMethodMapping.java | 15 +++-- .../handler/AbstractUrlHandlerMapping.java | 15 ++--- .../SimpleMappingExceptionResolver.java | 4 +- .../WebRequestHandlerInterceptorAdapter.java | 5 +- .../mvc/ParameterizableViewController.java | 3 +- .../servlet/mvc/WebContentInterceptor.java | 14 ++--- .../mvc/method/RequestMappingInfo.java | 3 +- .../annotation/HttpEntityMethodProcessor.java | 20 +++---- .../RequestResponseBodyAdviceChain.java | 9 ++- .../ResponseEntityExceptionHandler.java | 6 +- .../ViewMethodReturnValueHandler.java | 3 +- .../resource/CssLinkResourceTransformer.java | 5 +- .../resource/PathResourceResolver.java | 15 ++--- .../resource/ResourceHttpRequestHandler.java | 14 ++--- .../servlet/resource/ResourceUrlProvider.java | 3 +- .../resource/VersionResourceResolver.java | 8 +-- .../support/JspAwareRequestContext.java | 8 +-- .../web/servlet/support/RequestContext.java | 10 ++-- .../tags/form/SelectedValueComparator.java | 15 +++-- .../view/AbstractCachingViewResolver.java | 4 +- .../view/ContentNegotiatingViewResolver.java | 5 +- .../view/json/AbstractJackson2View.java | 5 +- .../view/script/ScriptTemplateView.java | 5 +- .../web/servlet/view/xslt/XsltView.java | 34 +++++------ 36 files changed, 185 insertions(+), 228 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java index c1a814589a..d0904bb8ac 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,10 +165,9 @@ public final class FlashMap extends HashMap implements Comparabl if (this == other) { return true; } - if (!(other instanceof FlashMap)) { + if (!(other instanceof FlashMap otherFlashMap)) { return false; } - FlashMap otherFlashMap = (FlashMap) other; return (super.equals(otherFlashMap) && ObjectUtils.nullSafeEquals(this.targetRequestPath, otherFlashMap.targetRequestPath) && this.targetRequestParams.equals(otherFlashMap.targetRequestParams)); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java index ea0f304318..36510490ad 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java @@ -507,8 +507,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic */ @Override public void setApplicationContext(ApplicationContext applicationContext) { - if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext) { - this.webApplicationContext = (WebApplicationContext) applicationContext; + if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext wac) { + this.webApplicationContext = wac; this.webApplicationContextInjected = true; } } @@ -565,18 +565,15 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; - if (wac instanceof ConfigurableWebApplicationContext) { - ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac; - if (!cwac.isActive()) { - // The context has not yet been refreshed -> provide services such as - // setting the parent context, setting the application context id, etc - if (cwac.getParent() == null) { - // The context instance was injected without an explicit parent -> set - // the root application context (if any; may be null) as the parent - cwac.setParent(rootContext); - } - configureAndRefreshWebApplicationContext(cwac); + if (wac instanceof ConfigurableWebApplicationContext cwac && !cwac.isActive()) { + // The context has not yet been refreshed -> provide services such as + // setting the parent context, setting the application context id, etc + if (cwac.getParent() == null) { + // The context instance was injected without an explicit parent -> set + // the root application context (if any; may be null) as the parent + cwac.setParent(rootContext); } + configureAndRefreshWebApplicationContext(cwac); } } if (wac == null) { @@ -693,8 +690,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); - if (env instanceof ConfigurableWebEnvironment) { - ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig()); + if (env instanceof ConfigurableWebEnvironment cwe) { + cwe.initPropertySources(getServletContext(), getServletConfig()); } postProcessWebApplicationContext(wac); @@ -824,10 +821,10 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic */ public void refresh() { WebApplicationContext wac = getWebApplicationContext(); - if (!(wac instanceof ConfigurableApplicationContext)) { + if (!(wac instanceof ConfigurableApplicationContext cac)) { throw new IllegalStateException("WebApplicationContext does not support refresh: " + wac); } - ((ConfigurableApplicationContext) wac).refresh(); + cac.refresh(); } /** @@ -862,8 +859,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic public void destroy() { getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'"); // Only call close() on WebApplicationContext if locally managed... - if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) { - ((ConfigurableApplicationContext) this.webApplicationContext).close(); + if (!this.webApplicationContextInjected && this.webApplicationContext instanceof ConfigurableApplicationContext cac) { + cac.close(); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java index 76f5cb3577..f90bf35cc0 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerExecutionChain.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,7 @@ public class HandlerExecutionChain { * @since 5.3 */ public HandlerExecutionChain(Object handler, List interceptorList) { - if (handler instanceof HandlerExecutionChain) { - HandlerExecutionChain originalChain = (HandlerExecutionChain) handler; + if (handler instanceof HandlerExecutionChain originalChain) { this.handler = originalChain.getHandler(); this.interceptorList.addAll(originalChain.interceptorList); } @@ -188,9 +187,8 @@ public class HandlerExecutionChain { void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) { for (int i = this.interceptorList.size() - 1; i >= 0; i--) { HandlerInterceptor interceptor = this.interceptorList.get(i); - if (interceptor instanceof AsyncHandlerInterceptor) { + if (interceptor instanceof AsyncHandlerInterceptor asyncInterceptor) { try { - AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) interceptor; asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler); } catch (Throwable ex) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java index 2684d24e5e..a4e4fa85ee 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -514,8 +514,7 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser { private ManagedList wrapLegacyResolvers(List list, ParserContext context) { ManagedList result = new ManagedList<>(); for (Object object : list) { - if (object instanceof BeanDefinitionHolder) { - BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object; + if (object instanceof BeanDefinitionHolder beanDef) { String className = beanDef.getBeanDefinition().getBeanClassName(); Assert.notNull(className, "No resolver class"); Class clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader()); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java index 3cedaf2144..1bfdd3d65c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import org.springframework.web.util.pattern.PathPattern; public class ViewControllerRegistry { @Nullable - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; private final List registrations = new ArrayList<>(4); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java index 87c414d277..14443da995 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,10 +53,10 @@ import org.springframework.web.servlet.view.script.ScriptTemplateViewResolver; public class ViewResolverRegistry { @Nullable - private ContentNegotiationManager contentNegotiationManager; + private final ContentNegotiationManager contentNegotiationManager; @Nullable - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; @Nullable private ContentNegotiatingViewResolver contentNegotiatingResolver; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ChangePathPatternParserVisitor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ChangePathPatternParserVisitor.java index 264a30bf67..9fbc37e013 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ChangePathPatternParserVisitor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ChangePathPatternParserVisitor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,8 +69,7 @@ class ChangePathPatternParserVisitor implements RouterFunctions.Visitor { } private void changeParser(RequestPredicate predicate) { - if (predicate instanceof Target) { - Target target = (Target) predicate; + if (predicate instanceof Target target) { target.changeParser(this.parser); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java index cf674214be..68326e0027 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java @@ -202,8 +202,7 @@ final class DefaultEntityResponseBuilder implements EntityResponse.Builder @SuppressWarnings({"rawtypes", "unchecked"}) @Override public EntityResponse build() { - if (this.entity instanceof CompletionStage) { - CompletionStage completionStage = (CompletionStage) this.entity; + if (this.entity instanceof CompletionStage completionStage) { return new CompletionStageEntityResponse(this.status, this.headers, this.cookies, completionStage, this.entityType); } @@ -264,7 +263,7 @@ final class DefaultEntityResponseBuilder implements EntityResponse.Builder return null; } - @SuppressWarnings({ "unchecked", "resource" }) + @SuppressWarnings({ "unchecked", "resource", "rawtypes" }) protected void writeEntityWithMessageConverters(Object entity, HttpServletRequest request, HttpServletResponse response, ServerResponse.Context context) throws ServletException, IOException { @@ -294,16 +293,14 @@ final class DefaultEntityResponseBuilder implements EntityResponse.Builder } for (HttpMessageConverter messageConverter : context.messageConverters()) { - if (messageConverter instanceof GenericHttpMessageConverter) { - GenericHttpMessageConverter genericMessageConverter = - (GenericHttpMessageConverter) messageConverter; + if (messageConverter instanceof GenericHttpMessageConverter genericMessageConverter) { if (genericMessageConverter.canWrite(entityType, entityClass, contentType)) { genericMessageConverter.write(entity, entityType, contentType, serverResponse); return; } } if (messageConverter.canWrite(entityClass, contentType)) { - ((HttpMessageConverter)messageConverter).write(entity, contentType, serverResponse); + ((HttpMessageConverter) messageConverter).write(entity, contentType, serverResponse); return; } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequest.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequest.java index c874c05d7a..81f3700dae 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequest.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequest.java @@ -70,6 +70,7 @@ import org.springframework.web.util.UriBuilder; * {@code ServerRequest} implementation based on a {@link HttpServletRequest}. * * @author Arjen Poutsma + * @author Sam Brannen * @since 5.2 */ class DefaultServerRequest implements ServerRequest { @@ -171,14 +172,12 @@ class DefaultServerRequest implements ServerRequest { } static Class bodyClass(Type type) { - if (type instanceof Class) { - return (Class) type; + if (type instanceof Class clazz) { + return clazz; } - if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - if (parameterizedType.getRawType() instanceof Class) { - return (Class) parameterizedType.getRawType(); - } + if (type instanceof ParameterizedType parameterizedType && + parameterizedType.getRawType() instanceof Class rawType) { + return rawType; } return Object.class; } @@ -188,11 +187,9 @@ class DefaultServerRequest implements ServerRequest { MediaType contentType = this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM); for (HttpMessageConverter messageConverter : this.messageConverters) { - if (messageConverter instanceof GenericHttpMessageConverter) { - GenericHttpMessageConverter genericMessageConverter = - (GenericHttpMessageConverter) messageConverter; + if (messageConverter instanceof GenericHttpMessageConverter genericMessageConverter) { if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) { - return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest); + return (T) genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest); } } if (messageConverter.canRead(bodyClass, contentType)) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java index e25a624599..d29a96271e 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java @@ -65,6 +65,7 @@ import org.springframework.web.util.pattern.PathPatternParser; * request matching operations, such as matching based on path, HTTP method, etc. * * @author Arjen Poutsma + * @author Sam Brannen * @since 5.2 */ public abstract class RequestPredicates { @@ -792,11 +793,11 @@ public abstract class RequestPredicates { @Override public void changeParser(PathPatternParser parser) { - if (this.left instanceof ChangePathPatternParserVisitor.Target) { - ((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser); + if (this.left instanceof ChangePathPatternParserVisitor.Target target) { + target.changeParser(parser); } - if (this.right instanceof ChangePathPatternParserVisitor.Target) { - ((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser); + if (this.right instanceof ChangePathPatternParserVisitor.Target target) { + target.changeParser(parser); } } @@ -837,8 +838,8 @@ public abstract class RequestPredicates { @Override public void changeParser(PathPatternParser parser) { - if (this.delegate instanceof ChangePathPatternParserVisitor.Target) { - ((ChangePathPatternParserVisitor.Target) this.delegate).changeParser(parser); + if (this.delegate instanceof ChangePathPatternParserVisitor.Target target) { + target.changeParser(parser); } } @@ -904,11 +905,11 @@ public abstract class RequestPredicates { @Override public void changeParser(PathPatternParser parser) { - if (this.left instanceof ChangePathPatternParserVisitor.Target) { - ((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser); + if (this.left instanceof ChangePathPatternParserVisitor.Target target) { + target.changeParser(parser); } - if (this.right instanceof ChangePathPatternParserVisitor.Target) { - ((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser); + if (this.right instanceof ChangePathPatternParserVisitor.Target target) { + target.changeParser(parser); } } @@ -923,7 +924,7 @@ public abstract class RequestPredicates { private final ServerRequest request; - private RequestPath requestPath; + private final RequestPath requestPath; private final Map attributes; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java index f100a8ad33..0f4f30ae32 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java @@ -68,6 +68,7 @@ import org.springframework.web.util.pattern.PathPatternParser; * * @author Juergen Hoeller * @author Rossen Stoyanchev + * @author Sam Brannen * @since 07.04.2003 * @see #getHandlerInternal * @see #setDefaultHandler @@ -179,8 +180,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport @SuppressWarnings("deprecation") public void setAlwaysUseFullPath(boolean alwaysUseFullPath) { this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath); - if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setAlwaysUseFullPath(alwaysUseFullPath); + if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setAlwaysUseFullPath(alwaysUseFullPath); } } @@ -193,8 +194,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport @SuppressWarnings("deprecation") public void setUrlDecode(boolean urlDecode) { this.urlPathHelper.setUrlDecode(urlDecode); - if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setUrlDecode(urlDecode); + if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setUrlDecode(urlDecode); } } @@ -207,8 +208,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport @SuppressWarnings("deprecation") public void setRemoveSemicolonContent(boolean removeSemicolonContent) { this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent); - if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setRemoveSemicolonContent(removeSemicolonContent); + if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setRemoveSemicolonContent(removeSemicolonContent); } } @@ -220,8 +221,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport public void setUrlPathHelper(UrlPathHelper urlPathHelper) { Assert.notNull(urlPathHelper, "UrlPathHelper must not be null"); this.urlPathHelper = urlPathHelper; - if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setUrlPathHelper(urlPathHelper); + if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setUrlPathHelper(urlPathHelper); } } @@ -242,8 +243,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport public void setPathMatcher(PathMatcher pathMatcher) { Assert.notNull(pathMatcher, "PathMatcher must not be null"); this.pathMatcher = pathMatcher; - if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setPathMatcher(pathMatcher); + if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setPathMatcher(pathMatcher); } } @@ -311,8 +312,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport public void setCorsConfigurationSource(CorsConfigurationSource source) { Assert.notNull(source, "CorsConfigurationSource must not be null"); this.corsConfigurationSource = source; - if (source instanceof UrlBasedCorsConfigurationSource) { - ((UrlBasedCorsConfigurationSource) source).setAllowInitLookupPath(false); + if (source instanceof UrlBasedCorsConfigurationSource urlConfigSource) { + urlConfigSource.setAllowInitLookupPath(false); } } @@ -437,11 +438,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport * @see WebRequestHandlerInterceptorAdapter */ protected HandlerInterceptor adaptInterceptor(Object interceptor) { - if (interceptor instanceof HandlerInterceptor) { - return (HandlerInterceptor) interceptor; + if (interceptor instanceof HandlerInterceptor handlerInterceptor) { + return handlerInterceptor; } - else if (interceptor instanceof WebRequestInterceptor) { - return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor); + else if (interceptor instanceof WebRequestInterceptor webRequestInterceptor) { + return new WebRequestHandlerInterceptorAdapter(webRequestInterceptor); } else { throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName()); @@ -467,8 +468,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport protected final MappedInterceptor[] getMappedInterceptors() { List mappedInterceptors = new ArrayList<>(this.adaptedInterceptors.size()); for (HandlerInterceptor interceptor : this.adaptedInterceptors) { - if (interceptor instanceof MappedInterceptor) { - mappedInterceptors.add((MappedInterceptor) interceptor); + if (interceptor instanceof MappedInterceptor mappedInterceptor) { + mappedInterceptors.add(mappedInterceptor); } } return (!mappedInterceptors.isEmpty() ? mappedInterceptors.toArray(new MappedInterceptor[0]) : null); @@ -502,8 +503,7 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport return null; } // Bean name or resolved handler? - if (handler instanceof String) { - String handlerName = (String) handler; + if (handler instanceof String handlerName) { handler = obtainApplicationContext().getBean(handlerName); } @@ -600,12 +600,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport * @see #getAdaptedInterceptors() */ protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { - HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ? - (HandlerExecutionChain) handler : new HandlerExecutionChain(handler)); + HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain handlerExecutionChain ? + handlerExecutionChain : new HandlerExecutionChain(handler)); for (HandlerInterceptor interceptor : this.adaptedInterceptors) { - if (interceptor instanceof MappedInterceptor) { - MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor; + if (interceptor instanceof MappedInterceptor mappedInterceptor) { if (mappedInterceptor.matches(request)) { chain.addInterceptor(mappedInterceptor.getInterceptor()); } @@ -622,8 +621,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport * @since 5.2 */ protected boolean hasCorsConfigurationSource(Object handler) { - if (handler instanceof HandlerExecutionChain) { - handler = ((HandlerExecutionChain) handler).getHandler(); + if (handler instanceof HandlerExecutionChain handlerExecutionChain) { + handler = handlerExecutionChain.getHandler(); } return (handler instanceof CorsConfigurationSource || this.corsConfigurationSource != null); } @@ -638,11 +637,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport @Nullable protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { Object resolvedHandler = handler; - if (handler instanceof HandlerExecutionChain) { - resolvedHandler = ((HandlerExecutionChain) handler).getHandler(); + if (handler instanceof HandlerExecutionChain handlerExecutionChain) { + resolvedHandler = handlerExecutionChain.getHandler(); } - if (resolvedHandler instanceof CorsConfigurationSource) { - return ((CorsConfigurationSource) resolvedHandler).getCorsConfiguration(request); + if (resolvedHandler instanceof CorsConfigurationSource configSource) { + return configSource.getCorsConfiguration(request); } return null; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodExceptionResolver.java index 47acaf4bc5..00ecd4f690 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHan if (handler == null) { return super.shouldApplyTo(request, null); } - else if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; + else if (handler instanceof HandlerMethod handlerMethod) { handler = handlerMethod.getBean(); return super.shouldApplyTo(request, handler); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java index 2073087a15..39480d9147 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java @@ -273,8 +273,8 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap * @see #getMappingForMethod */ protected void detectHandlerMethods(Object handler) { - Class handlerType = (handler instanceof String ? - obtainApplicationContext().getType((String) handler) : handler.getClass()); + Class handlerType = (handler instanceof String beanName ? + obtainApplicationContext().getType(beanName) : handler.getClass()); if (handlerType != null) { Class userType = ClassUtils.getUserClass(handlerType); @@ -339,8 +339,8 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap * @return the created HandlerMethod */ protected HandlerMethod createHandlerMethod(Object handler, Method method) { - if (handler instanceof String) { - return new HandlerMethod((String) handler, + if (handler instanceof String beanName) { + return new HandlerMethod(beanName, obtainApplicationContext().getAutowireCapableBeanFactory(), obtainApplicationContext(), method); @@ -479,15 +479,14 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap @Override protected boolean hasCorsConfigurationSource(Object handler) { return super.hasCorsConfigurationSource(handler) || - (handler instanceof HandlerMethod && - this.mappingRegistry.getCorsConfiguration((HandlerMethod) handler) != null); + (handler instanceof HandlerMethod handerMethod && + this.mappingRegistry.getCorsConfiguration(handerMethod) != null); } @Override protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { CorsConfiguration corsConfig = super.getCorsConfiguration(handler, request); - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; + if (handler instanceof HandlerMethod handlerMethod) { if (handlerMethod.equals(PREFLIGHT_AMBIGUOUS_MATCH)) { return AbstractHandlerMethodMapping.ALLOW_CORS_CONFIG; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java index f244dfdada..812855a1f1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractUrlHandlerMapping.java @@ -163,8 +163,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i } if (rawHandler != null) { // Bean name or resolved handler? - if (rawHandler instanceof String) { - String handlerName = (String) rawHandler; + if (rawHandler instanceof String handlerName) { rawHandler = obtainApplicationContext().getBean(handlerName); } validateHandler(rawHandler, request); @@ -211,8 +210,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i } PathPattern pattern = matches.get(0); handler = this.pathPatternHandlerMap.get(pattern); - if (handler instanceof String) { - String handlerName = (String) handler; + if (handler instanceof String handlerName) { handler = obtainApplicationContext().getBean(handlerName); } validateHandler(handler, request); @@ -270,8 +268,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i } } // Bean name or resolved handler? - if (handler instanceof String) { - String handlerName = (String) handler; + if (handler instanceof String handlerName) { handler = obtainApplicationContext().getBean(handlerName); } validateHandler(handler, request); @@ -302,8 +299,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i Object handler = this.handlerMap.get(urlPath); if (handler != null) { // Bean name or resolved handler? - if (handler instanceof String) { - String handlerName = (String) handler; + if (handler instanceof String handlerName) { handler = obtainApplicationContext().getBean(handlerName); } validateHandler(handler, request); @@ -413,8 +409,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i Object resolvedHandler = handler; // Eagerly resolve handler if referencing singleton via name. - if (!this.lazyInitHandlers && handler instanceof String) { - String handlerName = (String) handler; + if (!this.lazyInitHandlers && handler instanceof String handlerName) { ApplicationContext applicationContext = obtainApplicationContext(); if (applicationContext.isSingleton(handlerName)) { resolvedHandler = applicationContext.getBean(handlerName); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java index 61645c5c8d..c6f90e8c64 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ public class SimpleMappingExceptionResolver extends AbstractHandlerExceptionReso @Nullable private Integer defaultStatusCode; - private Map statusCodes = new HashMap<>(); + private final Map statusCodes = new HashMap<>(); @Nullable private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/WebRequestHandlerInterceptorAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/WebRequestHandlerInterceptorAdapter.java index a3028dcb27..80ff163790 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/WebRequestHandlerInterceptorAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/WebRequestHandlerInterceptorAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,8 +75,7 @@ public class WebRequestHandlerInterceptorAdapter implements AsyncHandlerIntercep @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) { - if (this.requestInterceptor instanceof AsyncWebRequestInterceptor) { - AsyncWebRequestInterceptor asyncInterceptor = (AsyncWebRequestInterceptor) this.requestInterceptor; + if (this.requestInterceptor instanceof AsyncWebRequestInterceptor asyncInterceptor) { DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, response); asyncInterceptor.afterConcurrentHandlingStarted(webRequest); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ParameterizableViewController.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ParameterizableViewController.java index 6cf029898c..dd43a0ae3a 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ParameterizableViewController.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ParameterizableViewController.java @@ -67,8 +67,7 @@ public class ParameterizableViewController extends AbstractController { */ @Nullable public String getViewName() { - if (this.view instanceof String) { - String viewName = (String) this.view; + if (this.view instanceof String viewName) { if (getStatusCode() != null && getStatusCode().is3xxRedirection()) { return viewName.startsWith("redirect:") ? viewName : "redirect:" + viewName; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java index 450ec25c9a..b0e94f7f0b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/WebContentInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,9 +80,9 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle private PathMatcher pathMatcher = defaultPathMatcher; - private Map cacheMappings = new HashMap<>(); + private final Map cacheMappings = new HashMap<>(); - private Map cacheControlMappings = new HashMap<>(); + private final Map cacheControlMappings = new HashMap<>(); /** @@ -215,8 +215,8 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle } if (!ObjectUtils.isEmpty(this.cacheControlMappings)) { - CacheControl control = (path instanceof PathContainer ? - lookupCacheControl((PathContainer) path) : lookupCacheControl((String) path)); + CacheControl control = (path instanceof PathContainer pathContainer ? + lookupCacheControl(pathContainer) : lookupCacheControl((String) path)); if (control != null) { if (logger.isTraceEnabled()) { logger.trace("Applying " + control); @@ -227,8 +227,8 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle } if (!ObjectUtils.isEmpty(this.cacheMappings)) { - Integer cacheSeconds = (path instanceof PathContainer ? - lookupCacheSeconds((PathContainer) path) : lookupCacheSeconds((String) path)); + Integer cacheSeconds = (path instanceof PathContainer pathContainer ? + lookupCacheSeconds(pathContainer) : lookupCacheSeconds((String) path)); if (cacheSeconds != null) { if (logger.isTraceEnabled()) { logger.trace("Applying cacheSeconds " + cacheSeconds); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java index 615ce11494..3adf3ca633 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java @@ -470,10 +470,9 @@ public final class RequestMappingInfo implements RequestCondition responseEntity = (HttpEntity) returnValue; + HttpEntity httpEntity = (HttpEntity) returnValue; HttpHeaders outputHeaders = outputMessage.getHeaders(); - HttpHeaders entityHeaders = responseEntity.getHeaders(); + HttpHeaders entityHeaders = httpEntity.getHeaders(); if (!entityHeaders.isEmpty()) { entityHeaders.forEach((key, value) -> { if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) { @@ -196,8 +196,8 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro }); } - if (responseEntity instanceof ResponseEntity) { - int returnStatus = ((ResponseEntity) responseEntity).getStatusCodeValue(); + if (httpEntity instanceof ResponseEntity responseEntity) { + int returnStatus = responseEntity.getStatusCodeValue(); outputMessage.getServletResponse().setStatus(returnStatus); if (returnStatus == 200) { HttpMethod method = inputMessage.getMethod(); @@ -216,7 +216,7 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro } // Try even with null body. ResponseBodyAdvice could get involved. - writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage); + writeWithMessageConverters(httpEntity.getBody(), returnType, inputMessage, outputMessage); // Ensure headers are flushed even if no body was written. outputMessage.flush(); @@ -261,8 +261,8 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro private void saveFlashAttributes(ModelAndViewContainer mav, NativeWebRequest request, String location) { mav.setRedirectModelScenario(true); ModelMap model = mav.getModel(); - if (model instanceof RedirectAttributes) { - Map flashAttributes = ((RedirectAttributes) model).getFlashAttributes(); + if (model instanceof RedirectAttributes redirectAttributes) { + Map flashAttributes = redirectAttributes.getFlashAttributes(); if (!CollectionUtils.isEmpty(flashAttributes)) { HttpServletRequest req = request.getNativeRequest(HttpServletRequest.class); HttpServletResponse res = request.getNativeResponse(HttpServletResponse.class); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChain.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChain.java index f72115ab82..f5e4834907 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChain.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyAdviceChain.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,8 @@ class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyA if (requestResponseBodyAdvice != null) { List result = new ArrayList<>(); for (Object advice : requestResponseBodyAdvice) { - Class beanType = (advice instanceof ControllerAdviceBean ? - ((ControllerAdviceBean) advice).getBeanType() : advice.getClass()); + Class beanType = (advice instanceof ControllerAdviceBean adviceBean ? + adviceBean.getBeanType() : advice.getClass()); if (beanType != null && adviceType.isAssignableFrom(beanType)) { result.add((T) advice); } @@ -153,8 +153,7 @@ class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyA } List result = new ArrayList<>(availableAdvice.size()); for (Object advice : availableAdvice) { - if (advice instanceof ControllerAdviceBean) { - ControllerAdviceBean adviceBean = (ControllerAdviceBean) advice; + if (advice instanceof ControllerAdviceBean adviceBean) { if (!adviceBean.isApplicableToBeanType(parameter.getContainingClass())) { continue; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java index 2c96722b14..c4f3076efa 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java @@ -230,8 +230,7 @@ public abstract class ResponseEntityExceptionHandler { List mediaTypes = ex.getSupportedMediaTypes(); if (!CollectionUtils.isEmpty(mediaTypes)) { headers.setAccept(mediaTypes); - if (request instanceof ServletWebRequest) { - ServletWebRequest servletWebRequest = (ServletWebRequest) request; + if (request instanceof ServletWebRequest servletWebRequest) { if (HttpMethod.PATCH.equals(servletWebRequest.getHttpMethod())) { headers.setAcceptPatch(mediaTypes); } @@ -437,8 +436,7 @@ public abstract class ResponseEntityExceptionHandler { protected ResponseEntity handleAsyncRequestTimeoutException( AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) { - if (webRequest instanceof ServletWebRequest) { - ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest; + if (webRequest instanceof ServletWebRequest servletWebRequest) { HttpServletResponse response = servletWebRequest.getResponse(); if (response != null && response.isCommitted()) { if (logger.isWarnEnabled()) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java index 4934ea9a52..80d63ad1f1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ViewMethodReturnValueHandler.java @@ -50,8 +50,7 @@ public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHan public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { - if (returnValue instanceof View) { - View view = (View) returnValue; + if (returnValue instanceof View view) { mavContainer.setView(view); if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { mavContainer.setRedirectModelScenario(true); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java index e27e2ac1da..3193814625 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -235,10 +235,9 @@ public class CssLinkResourceTransformer extends ResourceTransformerSupport { if (this == other) { return true; } - if (!(other instanceof ContentChunkInfo)) { + if (!(other instanceof ContentChunkInfo otherCci)) { return false; } - ContentChunkInfo otherCci = (ContentChunkInfo) other; return (this.start == otherCci.start && this.end == otherCci.end); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java index 34c782c529..002705603f 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java @@ -237,12 +237,12 @@ public class PathResourceResolver extends AbstractResourceResolver { resourcePath = resource.getURL().toExternalForm(); locationPath = StringUtils.cleanPath(location.getURL().toString()); } - else if (resource instanceof ClassPathResource) { - resourcePath = ((ClassPathResource) resource).getPath(); + else if (resource instanceof ClassPathResource classPathResource) { + resourcePath = classPathResource.getPath(); locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath()); } - else if (resource instanceof ServletContextResource) { - resourcePath = ((ServletContextResource) resource).getPath(); + else if (resource instanceof ServletContextResource servletContextResource) { + resourcePath = servletContextResource.getPath(); locationPath = StringUtils.cleanPath(((ServletContextResource) location).getPath()); } else { @@ -301,11 +301,8 @@ public class PathResourceResolver extends AbstractResourceResolver { return true; } } - catch (IllegalArgumentException ex) { - // May not be possible to decode... - } - catch (UnsupportedEncodingException ex) { - // Should never happen... + catch (IllegalArgumentException | UnsupportedEncodingException ex) { + // May not be possible to decode... | Should never happen... } } return false; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java index 87cf98da13..f0455d303c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java @@ -484,8 +484,7 @@ public class ResourceHttpRequestHandler extends WebContentGenerator return; } for (int i = getResourceResolvers().size() - 1; i >= 0; i--) { - if (getResourceResolvers().get(i) instanceof PathResourceResolver) { - PathResourceResolver pathResolver = (PathResourceResolver) getResourceResolvers().get(i); + if (getResourceResolvers().get(i) instanceof PathResourceResolver pathResolver) { if (ObjectUtils.isEmpty(pathResolver.getAllowedLocations())) { pathResolver.setAllowedLocations(getLocations().toArray(new Resource[0])); } @@ -681,11 +680,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator return true; } } - catch (IllegalArgumentException ex) { - // May not be possible to decode... - } - catch (UnsupportedEncodingException ex) { - // Should never happen... + catch (IllegalArgumentException | UnsupportedEncodingException ex) { + // May not be possible to decode... | Should never happen... } } return false; @@ -788,8 +784,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator response.setContentType(mediaType.toString()); } - if (resource instanceof HttpResource) { - HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders(); + if (resource instanceof HttpResource httpResource) { + HttpHeaders resourceHeaders = httpResource.getResponseHeaders(); resourceHeaders.forEach((headerName, headerValues) -> { boolean first = true; for (String headerValue : headerValues) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java index 7a2a6e2a67..afd47b83b3 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java @@ -154,8 +154,7 @@ public class ResourceUrlProvider implements ApplicationListener VersionStrategy. */ private final Map versionStrategyMap = new LinkedHashMap<>(); @@ -311,8 +311,8 @@ public class VersionResourceResolver extends AbstractResourceResolver { @Override public HttpHeaders getResponseHeaders() { - HttpHeaders headers = (this.original instanceof HttpResource ? - ((HttpResource) this.original).getResponseHeaders() : new HttpHeaders()); + HttpHeaders headers = (this.original instanceof HttpResource httpResource ? + httpResource.getResponseHeaders() : new HttpHeaders()); headers.setETag("W/\"" + this.version + "\""); return headers; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java index b02d169ea8..b0f3e2bd04 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ import org.springframework.lang.Nullable; */ public class JspAwareRequestContext extends RequestContext { - private PageContext pageContext; + private final PageContext pageContext; /** @@ -115,13 +115,13 @@ public class JspAwareRequestContext extends RequestContext { @Nullable public static Locale getJstlLocale(PageContext pageContext) { Object localeObject = Config.find(pageContext, Config.FMT_LOCALE); - return (localeObject instanceof Locale ? (Locale) localeObject : null); + return (localeObject instanceof Locale locale ? locale : null); } @Nullable public static TimeZone getJstlTimeZone(PageContext pageContext) { Object timeZoneObject = Config.find(pageContext, Config.FMT_TIME_ZONE); - return (timeZoneObject instanceof TimeZone ? (TimeZone) timeZoneObject : null); + return (timeZoneObject instanceof TimeZone timeZone ? timeZone : null); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java index db97efc2ba..2de52f3cbc 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java @@ -95,15 +95,15 @@ public class RequestContext { protected static final boolean jstlPresent = ClassUtils.isPresent( "jakarta.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader()); - private HttpServletRequest request; + private final HttpServletRequest request; @Nullable - private HttpServletResponse response; + private final HttpServletResponse response; @Nullable - private Map model; + private final Map model; - private WebApplicationContext webApplicationContext; + private final WebApplicationContext webApplicationContext; @Nullable private Locale locale; @@ -118,7 +118,7 @@ public class RequestContext { private Boolean defaultHtmlEscape; @Nullable - private Boolean responseEncodedHtmlEscape; + private final Boolean responseEncodedHtmlEscape; private UrlPathHelper urlPathHelper; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java index 3ad6c33b9c..f8b41e0295 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import org.springframework.web.servlet.support.BindStatus; * *

Equality Contract

* For single-valued objects equality is first tested using standard {@link Object#equals Java equality}. As - * such, user code should endeavour to implement {@link Object#equals} to speed up the comparison process. If + * such, user code should endeavor to implement {@link Object#equals} to speed up the comparison process. If * {@link Object#equals} returns {@code false} then an attempt is made at an * {@link #exhaustiveCompare exhaustive comparison} with the aim being to prove equality rather * than disprove it. @@ -86,11 +86,11 @@ abstract class SelectedValueComparator { if (boundValue.getClass().isArray()) { selected = collectionCompare(CollectionUtils.arrayToList(boundValue), candidateValue, bindStatus); } - else if (boundValue instanceof Collection) { - selected = collectionCompare((Collection) boundValue, candidateValue, bindStatus); + else if (boundValue instanceof Collection collection) { + selected = collectionCompare(collection, candidateValue, bindStatus); } - else if (boundValue instanceof Map) { - selected = mapCompare((Map) boundValue, candidateValue, bindStatus); + else if (boundValue instanceof Map map) { + selected = mapCompare(map, candidateValue, bindStatus); } } if (!selected) { @@ -163,9 +163,8 @@ abstract class SelectedValueComparator { return true; } - if (editor != null && candidate instanceof String) { + if (editor != null && candidate instanceof String candidateAsString) { // Try PE-based comparison (PE should *not* be allowed to escape creating thread) - String candidateAsString = (String) candidate; Object candidateAsValue; if (convertedValueCache != null && convertedValueCache.containsKey(editor)) { candidateAsValue = convertedValueCache.get(editor); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java index d7bf2fa337..53cfc10f27 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,7 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu /** Map from view key to View instance, synchronized for View creation. */ @SuppressWarnings("serial") private final Map viewCreationCache = - new LinkedHashMap(DEFAULT_CACHE_LIMIT, 0.75f, true) { + new LinkedHashMap<>(DEFAULT_CACHE_LIMIT, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { if (size() > getCacheLimit()) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java index 3c1699a5ab..4fdb0a2c88 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -332,8 +332,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport @Nullable private View getBestView(List candidateViews, List requestedMediaTypes, RequestAttributes attrs) { for (View candidateView : candidateViews) { - if (candidateView instanceof SmartView) { - SmartView smartView = (SmartView) candidateView; + if (candidateView instanceof SmartView smartView) { if (smartView.isRedirectView()) { return candidateView; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/AbstractJackson2View.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/AbstractJackson2View.java index e85cea4415..176cf840a5 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/AbstractJackson2View.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/AbstractJackson2View.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -212,8 +212,7 @@ public abstract class AbstractJackson2View extends AbstractView { Class serializationView = null; FilterProvider filters = null; - if (value instanceof MappingJacksonValue) { - MappingJacksonValue container = (MappingJacksonValue) value; + if (value instanceof MappingJacksonValue container) { value = container.getValue(); serializationView = container.getSerializationView(); filters = container.getFilters(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java index 57e627e89c..f7626a9deb 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -470,10 +470,9 @@ public class ScriptTemplateView extends AbstractUrlBasedView { if (this == other) { return true; } - if (!(other instanceof EngineKey)) { + if (!(other instanceof EngineKey otherKey)) { return false; } - EngineKey otherKey = (EngineKey) other; return (this.engineName.equals(otherKey.engineName) && Arrays.equals(this.scripts, otherKey.scripts)); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java index 1d3c29b939..e80d827832 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -302,32 +302,31 @@ public class XsltView extends AbstractUrlBasedView { /** * Convert the supplied {@link Object} into an XSLT {@link Source} if the * {@link Object} type is {@link #getSourceTypes() supported}. - * @param source the original source object + * @param sourceObject the original source object * @return the adapted XSLT Source * @throws IllegalArgumentException if the given Object is not of a supported type */ - protected Source convertSource(Object source) throws Exception { - if (source instanceof Source) { - return (Source) source; + protected Source convertSource(Object sourceObject) throws Exception { + if (sourceObject instanceof Source source) { + return source; } - else if (source instanceof Document) { - return new DOMSource(((Document) source).getDocumentElement()); + else if (sourceObject instanceof Document document) { + return new DOMSource(document.getDocumentElement()); } - else if (source instanceof Node) { - return new DOMSource((Node) source); + else if (sourceObject instanceof Node node) { + return new DOMSource(node); } - else if (source instanceof Reader) { - return new StreamSource((Reader) source); + else if (sourceObject instanceof Reader reader) { + return new StreamSource(reader); } - else if (source instanceof InputStream) { - return new StreamSource((InputStream) source); + else if (sourceObject instanceof InputStream inputStream) { + return new StreamSource(inputStream); } - else if (source instanceof Resource) { - Resource resource = (Resource) source; + else if (sourceObject instanceof Resource resource) { return new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString()); } else { - throw new IllegalArgumentException("Value '" + source + "' cannot be converted to XSLT Source"); + throw new IllegalArgumentException("Value '" + sourceObject + "' cannot be converted to XSLT Source"); } } @@ -481,8 +480,7 @@ public class XsltView extends AbstractUrlBasedView { * @param source the XSLT Source to close (may be {@code null}) */ private void closeSourceIfNecessary(@Nullable Source source) { - if (source instanceof StreamSource) { - StreamSource streamSource = (StreamSource) source; + if (source instanceof StreamSource streamSource) { if (streamSource.getReader() != null) { try { streamSource.getReader().close();