From ffe7ec4a99e2f8b55f7b46d2603b4356e8339246 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 7 Mar 2023 18:23:15 +0100 Subject: [PATCH] Apply "instanceof pattern matching" in remainder of spring-webmvc module See gh-30067 --- .../web/servlet/DispatcherServlet.java | 12 +-- .../web/servlet/ModelAndView.java | 6 +- .../web/servlet/config/MvcNamespaceUtils.java | 4 +- .../annotation/InterceptorRegistry.java | 6 +- .../function/DefaultAsyncServerResponse.java | 17 ++-- .../function/DefaultServerRequestBuilder.java | 8 +- .../function/ErrorHandlingServerResponse.java | 10 +-- .../function/HandlerFilterFunction.java | 6 +- .../function/PathResourceLookupFunction.java | 6 +- .../servlet/function/SseServerResponse.java | 6 +- .../support/HandlerFunctionAdapter.java | 12 +-- ...bstractHandlerMethodExceptionResolver.java | 4 +- .../handler/HandlerMappingIntrospector.java | 18 ++--- .../handler/SimpleServletPostProcessor.java | 10 +-- .../handler/SimpleUrlHandlerMapping.java | 6 +- .../mvc/HttpRequestHandlerAdapter.java | 6 +- .../mvc/ParameterizableViewController.java | 4 +- .../mvc/SimpleControllerHandlerAdapter.java | 6 +- .../ResponseStatusExceptionResolver.java | 10 +-- .../method/AbstractHandlerMethodAdapter.java | 4 +- .../mvc/method/RequestMappingInfo.java | 12 ++- .../RequestMappingInfoHandlerMapping.java | 4 +- ...tractMappingJacksonResponseBodyAdvice.java | 4 +- ...essageConverterMethodArgumentResolver.java | 12 +-- ...stractMessageConverterMethodProcessor.java | 10 +-- .../ExceptionHandlerExceptionResolver.java | 6 +- .../ModelAndViewMethodReturnValueHandler.java | 4 +- .../PathVariableMethodArgumentResolver.java | 6 +- ...ResponseBodyEmitterReturnValueHandler.java | 6 +- .../ServletInvocableHandlerMethod.java | 17 ++-- .../ViewMethodReturnValueHandler.java | 4 +- .../DefaultHandlerExceptionResolver.java | 78 ++++++++----------- .../resource/EncodedResourceResolver.java | 4 +- .../resource/ResourceUrlEncodingFilter.java | 6 +- .../web/servlet/support/JstlUtils.java | 10 +-- .../web/servlet/support/RequestContext.java | 26 +++---- .../web/servlet/tags/MessageTag.java | 14 ++-- .../web/servlet/tags/UrlTag.java | 6 +- .../form/AbstractDataBoundFormElementTag.java | 6 +- .../form/AbstractMultiCheckedElementTag.java | 6 +- .../web/servlet/tags/form/CheckboxTag.java | 6 +- .../web/servlet/tags/form/FormTag.java | 14 ++-- .../web/servlet/tags/form/OptionWriter.java | 8 +- .../web/servlet/view/RedirectView.java | 4 +- .../servlet/view/UrlBasedViewResolver.java | 6 +- .../web/servlet/view/xml/MarshallingView.java | 6 +- 46 files changed, 214 insertions(+), 232 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java index a5cca7b962..694e40eebf 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java @@ -812,8 +812,8 @@ public class DispatcherServlet extends FrameworkServlet { @Deprecated @Nullable public final org.springframework.ui.context.ThemeSource getThemeSource() { - return (getWebApplicationContext() instanceof org.springframework.ui.context.ThemeSource ? - (org.springframework.ui.context.ThemeSource) getWebApplicationContext() : null); + return (getWebApplicationContext() instanceof org.springframework.ui.context.ThemeSource themeSource ? + themeSource : null); } /** @@ -1143,9 +1143,9 @@ public class DispatcherServlet extends FrameworkServlet { boolean errorView = false; if (exception != null) { - if (exception instanceof ModelAndViewDefiningException) { + if (exception instanceof ModelAndViewDefiningException mavDefiningException) { logger.debug("ModelAndViewDefiningException encountered", exception); - mv = ((ModelAndViewDefiningException) exception).getModelAndView(); + mv = mavDefiningException.getModelAndView(); } else { Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); @@ -1188,8 +1188,8 @@ public class DispatcherServlet extends FrameworkServlet { @Override protected LocaleContext buildLocaleContext(final HttpServletRequest request) { LocaleResolver lr = this.localeResolver; - if (lr instanceof LocaleContextResolver) { - return ((LocaleContextResolver) lr).resolveLocaleContext(request); + if (lr instanceof LocaleContextResolver localeContextResolver) { + return localeContextResolver.resolveLocaleContext(request); } else { return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale()); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndView.java index d7e1e4ef20..1de142487b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -195,7 +195,7 @@ public class ModelAndView { */ @Nullable public String getViewName() { - return (this.view instanceof String ? (String) this.view : null); + return (this.view instanceof String name ? name : null); } /** @@ -212,7 +212,7 @@ public class ModelAndView { */ @Nullable public View getView() { - return (this.view instanceof View ? (View) this.view : null); + return (this.view instanceof View v ? v : null); } /** diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceUtils.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceUtils.java index e6ac91ad60..fcf9054751 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceUtils.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/MvcNamespaceUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -303,7 +303,7 @@ public abstract class MvcNamespaceUtils { */ private static boolean containsBeanInHierarchy(ParserContext context, String beanName) { BeanDefinitionRegistry registry = context.getRegistry(); - return (registry instanceof BeanFactory ? ((BeanFactory) registry).containsBean(beanName) : + return (registry instanceof BeanFactory beanFactory ? beanFactory.containsBean(beanName) : registry.containsBeanDefinition(beanName)); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java index 5e5d607007..2b4813f6b8 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,8 @@ public class InterceptorRegistry { private static final Comparator INTERCEPTOR_ORDER_COMPARATOR = OrderComparator.INSTANCE.withSourceProvider(object -> { - if (object instanceof InterceptorRegistration) { - return (Ordered) ((InterceptorRegistration) object)::getOrder; + if (object instanceof InterceptorRegistration interceptorRegistration) { + return (Ordered) interceptorRegistration::getOrder; } return null; }); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java index 0fefc59a91..c022b4daa0 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -168,19 +168,18 @@ final class DefaultAsyncServerResponse extends ErrorHandlingServerResponse imple return result; } - @SuppressWarnings({"unchecked"}) - public static AsyncServerResponse create(Object o, @Nullable Duration timeout) { - Assert.notNull(o, "Argument to async must not be null"); + @SuppressWarnings({"unchecked", "rawtypes"}) + public static AsyncServerResponse create(Object obj, @Nullable Duration timeout) { + Assert.notNull(obj, "Argument to async must not be null"); - if (o instanceof CompletableFuture) { - CompletableFuture futureResponse = (CompletableFuture) o; + if (obj instanceof CompletableFuture futureResponse) { return new DefaultAsyncServerResponse(futureResponse, timeout); } else if (reactiveStreamsPresent) { ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance(); - ReactiveAdapter publisherAdapter = registry.getAdapter(o.getClass()); + ReactiveAdapter publisherAdapter = registry.getAdapter(obj.getClass()); if (publisherAdapter != null) { - Publisher publisher = publisherAdapter.toPublisher(o); + Publisher publisher = publisherAdapter.toPublisher(obj); ReactiveAdapter futureAdapter = registry.getAdapter(CompletableFuture.class); if (futureAdapter != null) { CompletableFuture futureResponse = @@ -189,7 +188,7 @@ final class DefaultAsyncServerResponse extends ErrorHandlingServerResponse imple } } } - throw new IllegalArgumentException("Asynchronous type not supported: " + o.getClass()); + throw new IllegalArgumentException("Asynchronous type not supported: " + obj.getClass()); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequestBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequestBuilder.java index e771d3cbc7..e08e4005ee 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequestBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerRequestBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -299,11 +299,9 @@ class DefaultServerRequestBuilder implements ServerRequest.Builder { MediaType contentType = 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, inputMessage); + return (T) genericMessageConverter.read(bodyType, bodyClass, inputMessage); } } if (messageConverter.canRead(bodyClass, contentType)) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java index bce77dbe4c..81d9a19254 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,11 +60,11 @@ abstract class ErrorHandlingServerResponse implements ServerResponse { if (serverResponse != null) { return serverResponse.writeTo(servletRequest, servletResponse, context); } - else if (t instanceof ServletException) { - throw (ServletException) t; + else if (t instanceof ServletException servletException) { + throw servletException; } - else if (t instanceof IOException) { - throw (IOException) t; + else if (t instanceof IOException ioException ) { + throw ioException; } else { throw new ServletException(t); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/HandlerFilterFunction.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/HandlerFilterFunction.java index f27667592a..2186cc3371 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/HandlerFilterFunction.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/HandlerFilterFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -112,8 +112,8 @@ public interface HandlerFilterFunction { try { T t = next.handle(request); - if (t instanceof ErrorHandlingServerResponse) { - ((ErrorHandlingServerResponse) t).addErrorHandler(predicate, errorHandler); + if (t instanceof ErrorHandlingServerResponse response) { + response.addErrorHandler(predicate, errorHandler); } return t; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/PathResourceLookupFunction.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/PathResourceLookupFunction.java index c37bbfdce9..7195107f12 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/function/PathResourceLookupFunction.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/function/PathResourceLookupFunction.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,8 +125,8 @@ class PathResourceLookupFunction implements Function { - if (matchedMapping instanceof MatchableHandlerMapping) { + if (matchedMapping instanceof MatchableHandlerMapping matchableHandlerMapping) { PathPatternMatchableHandlerMapping mapping = this.pathPatternHandlerMappings.get(matchedMapping); if (mapping != null) { RequestPath requestPath = ServletRequestPathUtils.getParsedRequestPath(wrappedRequest); @@ -129,7 +129,7 @@ public class HandlerMappingIntrospector } else { String lookupPath = (String) wrappedRequest.getAttribute(UrlPathHelper.PATH_ATTRIBUTE); - return new PathSettingHandlerMapping((MatchableHandlerMapping) matchedMapping, lookupPath); + return new PathSettingHandlerMapping(matchableHandlerMapping, lookupPath); } } throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping"); @@ -142,12 +142,12 @@ public class HandlerMappingIntrospector AttributesPreservingRequest wrappedRequest = new AttributesPreservingRequest(request); return doWithMatchingMappingIgnoringException(wrappedRequest, (handlerMapping, executionChain) -> { for (HandlerInterceptor interceptor : executionChain.getInterceptorList()) { - if (interceptor instanceof CorsConfigurationSource) { - return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrappedRequest); + if (interceptor instanceof CorsConfigurationSource ccs) { + return ccs.getCorsConfiguration(wrappedRequest); } } - if (executionChain.getHandler() instanceof CorsConfigurationSource) { - return ((CorsConfigurationSource) executionChain.getHandler()).getCorsConfiguration(wrappedRequest); + if (executionChain.getHandler() instanceof CorsConfigurationSource ccs) { + return ccs.getCorsConfiguration(wrappedRequest); } return null; }); @@ -246,8 +246,8 @@ public class HandlerMappingIntrospector List mappings) { return mappings.stream() - .filter(mapping -> mapping instanceof MatchableHandlerMapping) - .map(mapping -> (MatchableHandlerMapping) mapping) + .filter(MatchableHandlerMapping.class::isInstance) + .map(MatchableHandlerMapping.class::cast) .filter(mapping -> mapping.getPatternParser() != null) .collect(Collectors.toMap(mapping -> mapping, PathPatternMatchableHandlerMapping::new)); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java index bfab08397d..2e7e31e553 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,13 +107,13 @@ public class SimpleServletPostProcessor implements @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof Servlet) { + if (bean instanceof Servlet servlet) { ServletConfig config = this.servletConfig; if (config == null || !this.useSharedServletConfig) { config = new DelegatingServletConfig(beanName, this.servletContext); } try { - ((Servlet) bean).init(config); + servlet.init(config); } catch (ServletException ex) { throw new BeanInitializationException("Servlet.init threw exception", ex); @@ -124,8 +124,8 @@ public class SimpleServletPostProcessor implements @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { - if (bean instanceof Servlet) { - ((Servlet) bean).destroy(); + if (bean instanceof Servlet servlet) { + servlet.destroy(); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java index 7cf819cf65..1e514c2d2b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleUrlHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,8 +155,8 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping { url = "/" + url; } // Remove whitespace from handler bean name. - if (handler instanceof String) { - handler = ((String) handler).trim(); + if (handler instanceof String handlerName) { + handler = handlerName.trim(); } registerHandler(url, handler); }); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/HttpRequestHandlerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/HttpRequestHandlerAdapter.java index 8fef024bce..835b7581f7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/HttpRequestHandlerAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/HttpRequestHandlerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,8 +56,8 @@ public class HttpRequestHandlerAdapter implements HandlerAdapter { @Override @SuppressWarnings("deprecation") public long getLastModified(HttpServletRequest request, Object handler) { - if (handler instanceof LastModified) { - return ((LastModified) handler).getLastModified(request); + if (handler instanceof LastModified lastModified) { + return lastModified.getLastModified(request); } return -1L; } 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 ac55f909d1..33dbf0deff 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,7 +95,7 @@ public class ParameterizableViewController extends AbstractController { */ @Nullable public View getView() { - return (this.view instanceof View ? (View) this.view : null); + return (this.view instanceof View v ? v : null); } /** diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/SimpleControllerHandlerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/SimpleControllerHandlerAdapter.java index a8acd760ec..58e4a57375 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/SimpleControllerHandlerAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/SimpleControllerHandlerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,8 +54,8 @@ public class SimpleControllerHandlerAdapter implements HandlerAdapter { @Override @SuppressWarnings("deprecation") public long getLastModified(HttpServletRequest request, Object handler) { - if (handler instanceof LastModified) { - return ((LastModified) handler).getLastModified(request); + if (handler instanceof LastModified lastModified) { + return lastModified.getLastModified(request); } return -1L; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java index 59e5caa36a..86f2ff658d 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,8 +72,8 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { try { - if (ex instanceof ResponseStatusException) { - return resolveResponseStatusException((ResponseStatusException) ex, request, response, handler); + if (ex instanceof ResponseStatusException rse) { + return resolveResponseStatusException(rse, request, response, handler); } ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class); @@ -81,8 +81,8 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes return resolveResponseStatus(status, request, response, handler, ex); } - if (ex.getCause() instanceof Exception) { - return doResolveException(request, response, handler, (Exception) ex.getCause()); + if (ex.getCause() instanceof Exception cause) { + return doResolveException(request, response, handler, cause); } } catch (Exception resolveEx) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/AbstractHandlerMethodAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/AbstractHandlerMethodAdapter.java index 5d613bb86b..c734fe5e83 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/AbstractHandlerMethodAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/AbstractHandlerMethodAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ public abstract class AbstractHandlerMethodAdapter extends WebContentGenerator i */ @Override public final boolean supports(Object handler) { - return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler)); + return (handler instanceof HandlerMethod handlerMethod && supportsInternal(handlerMethod)); } /** 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 916d8e093b..a9c5725af6 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -240,9 +240,8 @@ public final class RequestMappingInfo implements RequestCondition getDirectPaths() { RequestCondition condition = getActivePatternsCondition(); - return (condition instanceof PathPatternsRequestCondition ? - ((PathPatternsRequestCondition) condition).getDirectPaths() : - ((PatternsRequestCondition) condition).getDirectPaths()); + return (condition instanceof PathPatternsRequestCondition pprc ? + pprc.getDirectPaths() : ((PatternsRequestCondition) condition).getDirectPaths()); } /** @@ -252,9 +251,8 @@ public final class RequestMappingInfo implements RequestCondition getPatternValues() { RequestCondition condition = getActivePatternsCondition(); - return (condition instanceof PathPatternsRequestCondition ? - ((PathPatternsRequestCondition) condition).getPatternValues() : - ((PatternsRequestCondition) condition).getPatterns()); + return (condition instanceof PathPatternsRequestCondition pprc ? + pprc.getPatternValues() : ((PatternsRequestCondition) condition).getPatterns()); } /** diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java index a17418c185..ea3d01849c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java @@ -141,8 +141,8 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe super.handleMatch(info, lookupPath, request); RequestCondition condition = info.getActivePatternsCondition(); - if (condition instanceof PathPatternsRequestCondition) { - extractMatchDetails((PathPatternsRequestCondition) condition, lookupPath, request); + if (condition instanceof PathPatternsRequestCondition pprc) { + extractMatchDetails(pprc, lookupPath, request); } else { extractMatchDetails((PatternsRequestCondition) condition, lookupPath, request); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java index c84a56a798..56d831cb96 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ public abstract class AbstractMappingJacksonResponseBodyAdvice implements Respon * additional serialization instructions) or simply cast it if already wrapped. */ protected MappingJacksonValue getOrCreateContainer(Object body) { - return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body)); + return (body instanceof MappingJacksonValue mjv ? mjv : new MappingJacksonValue(body)); } /** diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java index 717ffa188c..39b71f6387 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java @@ -138,13 +138,13 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements * @throws IOException if the reading from the request fails * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found */ - @SuppressWarnings("unchecked") @Nullable + @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { Class contextClass = parameter.getContainingClass(); - Class targetClass = (targetType instanceof Class ? (Class) targetType : null); + Class targetClass = (targetType instanceof Class clazz ? clazz : null); if (targetClass == null) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); targetClass = (Class) resolvableType.resolve(); @@ -164,7 +164,7 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements contentType = MediaType.APPLICATION_OCTET_STREAM; } - HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null); + HttpMethod httpMethod = (inputMessage instanceof HttpRequest httpRequest ? httpRequest.getMethod() : null); Object body = NO_VALUE; EmptyBodyCheckingHttpInputMessage message = null; @@ -174,7 +174,7 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements for (HttpMessageConverter converter : this.messageConverters) { Class> converterType = (Class>) converter.getClass(); GenericHttpMessageConverter genericConverter = - (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter) converter : null); + (converter instanceof GenericHttpMessageConverter ghmc ? ghmc : null); if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) : (targetClass != null && converter.canRead(targetClass, contentType))) { if (message.hasBody()) { @@ -290,8 +290,8 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements @Nullable protected Object adaptArgumentIfNecessary(@Nullable Object arg, MethodParameter parameter) { if (parameter.getParameterType() == Optional.class) { - if (arg == null || (arg instanceof Collection && ((Collection) arg).isEmpty()) || - (arg instanceof Object[] && ((Object[]) arg).length == 0)) { + if (arg == null || (arg instanceof Collection collection && collection.isEmpty()) || + (arg instanceof Object[] array && array.length == 0)) { return Optional.empty(); } else { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java index d00b084c0d..3bf4dafbb2 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -280,8 +280,8 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe if (selectedMediaType != null) { selectedMediaType = selectedMediaType.removeQualityValue(); for (HttpMessageConverter converter : this.messageConverters) { - GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? - (GenericHttpMessageConverter) converter : null); + GenericHttpMessageConverter genericConverter = + (converter instanceof GenericHttpMessageConverter ghmc ? ghmc : null); if (genericConverter != null ? ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : converter.canWrite(valueType, selectedMediaType)) { @@ -383,8 +383,8 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe } Set result = new LinkedHashSet<>(); for (HttpMessageConverter converter : this.messageConverters) { - if (converter instanceof GenericHttpMessageConverter && targetType != null) { - if (((GenericHttpMessageConverter) converter).canWrite(targetType, valueClass, null)) { + if (converter instanceof GenericHttpMessageConverter ghmc && targetType != null) { + if (ghmc.canWrite(targetType, valueClass, null)) { result.addAll(converter.getSupportedMediaTypes(valueClass)); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java index 0588f57fe5..b296609588 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -433,8 +433,8 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce if (!mavContainer.isViewReference()) { mav.setView((View) mavContainer.getView()); } - if (model instanceof RedirectAttributes) { - Map flashAttributes = ((RedirectAttributes) model).getFlashAttributes(); + if (model instanceof RedirectAttributes redirectAttributes) { + Map flashAttributes = redirectAttributes.getFlashAttributes(); RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes); } return mav; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java index d1c1d07d7b..dbff025b50 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,7 +94,7 @@ public class ModelAndViewMethodReturnValueHandler implements HandlerMethodReturn else { View view = mav.getView(); mavContainer.setView(view); - if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { + if (view instanceof SmartView smartView && smartView.isRedirectView()) { mavContainer.setRedirectModelScenario(true); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java index 21a9fdb984..e35b49acb7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -139,8 +139,8 @@ public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethod @Nullable protected String formatUriValue(@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, Object value) { - if (value instanceof String) { - return (String) value; + if (value instanceof String string) { + return string; } else if (cs != null) { return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java index a401e30682..1667c210c5 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterReturnValueHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,8 +146,8 @@ public class ResponseBodyEmitterReturnValueHandler implements HandlerMethodRetur Assert.state(request != null, "No ServletRequest"); ResponseBodyEmitter emitter; - if (returnValue instanceof ResponseBodyEmitter) { - emitter = (ResponseBodyEmitter) returnValue; + if (returnValue instanceof ResponseBodyEmitter responseBodyEmitter) { + emitter = responseBodyEmitter; } else { emitter = this.reactiveHandler.handleValue(returnValue, returnType, mavContainer, webRequest); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java index 7f106c08f2..a7b93891f8 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,6 +45,7 @@ import org.springframework.web.method.support.HandlerMethodReturnValueHandlerCom import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.View; +import org.springframework.web.servlet.mvc.method.annotation.ReactiveTypeHandler.CollectedValuesList; /** * Extends {@link InvocableHandlerMethod} with the ability to handle return @@ -216,11 +217,11 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) { super((Callable) () -> { - if (result instanceof Exception) { - throw (Exception) result; + if (result instanceof Exception exception) { + throw exception; } - else if (result instanceof Throwable) { - throw new ServletException("Async processing failed: " + result, (Throwable) result); + else if (result instanceof Throwable throwable) { + throw new ServletException("Async processing failed: " + result, throwable); } return result; }, CALLABLE_METHOD); @@ -281,8 +282,8 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { public ConcurrentResultMethodParameter(Object returnValue) { super(-1); this.returnValue = returnValue; - this.returnType = (returnValue instanceof ReactiveTypeHandler.CollectedValuesList ? - ((ReactiveTypeHandler.CollectedValuesList) returnValue).getReturnType() : + this.returnType = (returnValue instanceof CollectedValuesList cvList ? + cvList.getReturnType() : KotlinDetector.isSuspendingFunction(super.getMethod()) ? ResolvableType.forMethodParameter(getReturnType()) : ResolvableType.forType(super.getGenericParameterType()).getGeneric()); @@ -316,7 +317,7 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { // even if actual return type is ResponseEntity> return (super.hasMethodAnnotation(annotationType) || (annotationType == ResponseBody.class && - this.returnValue instanceof ReactiveTypeHandler.CollectedValuesList)); + this.returnValue instanceof CollectedValuesList)); } @Override 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 80d63ad1f1..dbdb4364ae 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHan if (returnValue instanceof View view) { mavContainer.setView(view); - if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { + if (view instanceof SmartView smartView && smartView.isRedirectView()) { mavContainer.setRedirectModelScenario(true); } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java index 9a958ee7e0..dee6314ede 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.java @@ -169,73 +169,59 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes try { // ErrorResponse exceptions that expose HTTP response details - if (ex instanceof ErrorResponse) { + if (ex instanceof ErrorResponse errorResponse) { ModelAndView mav = null; - if (ex instanceof HttpRequestMethodNotSupportedException) { - mav = handleHttpRequestMethodNotSupported( - (HttpRequestMethodNotSupportedException) ex, request, response, handler); + if (ex instanceof HttpRequestMethodNotSupportedException theEx) { + mav = handleHttpRequestMethodNotSupported(theEx, request, response, handler); } - else if (ex instanceof HttpMediaTypeNotSupportedException) { - mav = handleHttpMediaTypeNotSupported( - (HttpMediaTypeNotSupportedException) ex, request, response, handler); + else if (ex instanceof HttpMediaTypeNotSupportedException theEx) { + mav = handleHttpMediaTypeNotSupported(theEx, request, response, handler); } - else if (ex instanceof HttpMediaTypeNotAcceptableException) { - mav = handleHttpMediaTypeNotAcceptable( - (HttpMediaTypeNotAcceptableException) ex, request, response, handler); + else if (ex instanceof HttpMediaTypeNotAcceptableException theEx) { + mav = handleHttpMediaTypeNotAcceptable(theEx, request, response, handler); } - else if (ex instanceof MissingPathVariableException) { - mav = handleMissingPathVariable( - (MissingPathVariableException) ex, request, response, handler); + else if (ex instanceof MissingPathVariableException theEx) { + mav = handleMissingPathVariable(theEx, request, response, handler); } - else if (ex instanceof MissingServletRequestParameterException) { - mav = handleMissingServletRequestParameter( - (MissingServletRequestParameterException) ex, request, response, handler); + else if (ex instanceof MissingServletRequestParameterException theEx) { + mav = handleMissingServletRequestParameter(theEx, request, response, handler); } - else if (ex instanceof MissingServletRequestPartException) { - mav = handleMissingServletRequestPartException( - (MissingServletRequestPartException) ex, request, response, handler); + else if (ex instanceof MissingServletRequestPartException theEx) { + mav = handleMissingServletRequestPartException(theEx, request, response, handler); } - else if (ex instanceof ServletRequestBindingException) { - mav = handleServletRequestBindingException( - (ServletRequestBindingException) ex, request, response, handler); + else if (ex instanceof ServletRequestBindingException theEx) { + mav = handleServletRequestBindingException(theEx, request, response, handler); } - else if (ex instanceof MethodArgumentNotValidException) { - mav = handleMethodArgumentNotValidException( - (MethodArgumentNotValidException) ex, request, response, handler); + else if (ex instanceof MethodArgumentNotValidException theEx) { + mav = handleMethodArgumentNotValidException(theEx, request, response, handler); } - else if (ex instanceof NoHandlerFoundException) { - mav = handleNoHandlerFoundException( - (NoHandlerFoundException) ex, request, response, handler); + else if (ex instanceof NoHandlerFoundException theEx) { + mav = handleNoHandlerFoundException(theEx, request, response, handler); } - else if (ex instanceof AsyncRequestTimeoutException) { - mav = handleAsyncRequestTimeoutException( - (AsyncRequestTimeoutException) ex, request, response, handler); + else if (ex instanceof AsyncRequestTimeoutException theEx) { + mav = handleAsyncRequestTimeoutException(theEx, request, response, handler); } return (mav != null ? mav : - handleErrorResponse((ErrorResponse) ex, request, response, handler)); + handleErrorResponse(errorResponse, request, response, handler)); } // Other, lower level exceptions - if (ex instanceof ConversionNotSupportedException) { - return handleConversionNotSupported( - (ConversionNotSupportedException) ex, request, response, handler); + if (ex instanceof ConversionNotSupportedException theEx) { + return handleConversionNotSupported(theEx, request, response, handler); } - else if (ex instanceof TypeMismatchException) { - return handleTypeMismatch( - (TypeMismatchException) ex, request, response, handler); + else if (ex instanceof TypeMismatchException theEx) { + return handleTypeMismatch(theEx, request, response, handler); } - else if (ex instanceof HttpMessageNotReadableException) { - return handleHttpMessageNotReadable( - (HttpMessageNotReadableException) ex, request, response, handler); + else if (ex instanceof HttpMessageNotReadableException theEx) { + return handleHttpMessageNotReadable(theEx, request, response, handler); } - else if (ex instanceof HttpMessageNotWritableException) { - return handleHttpMessageNotWritable( - (HttpMessageNotWritableException) ex, request, response, handler); + else if (ex instanceof HttpMessageNotWritableException theEx) { + return handleHttpMessageNotWritable(theEx, request, response, handler); } - else if (ex instanceof BindException) { - return handleBindException((BindException) ex, request, response, handler); + else if (ex instanceof BindException theEx) { + return handleBindException(theEx, request, response, handler); } } catch (Exception handlerEx) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResourceResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResourceResolver.java index 22350eebd6..f45d41c937 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResourceResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResourceResolver.java @@ -285,8 +285,8 @@ public class EncodedResourceResolver extends AbstractResourceResolver { @Override public HttpHeaders getResponseHeaders() { HttpHeaders headers; - if (this.original instanceof HttpResource) { - headers = ((HttpResource) this.original).getResponseHeaders(); + if (this.original instanceof HttpResource httpResource) { + headers = httpResource.getResponseHeaders(); } else { headers = new HttpHeaders(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java index 9360139abb..5bd3de0c6d 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,8 +85,8 @@ public class ResourceUrlEncodingFilter extends GenericFilterBean { public void setAttribute(String name, Object value) { super.setAttribute(name, value); if (ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR.equals(name)) { - if (value instanceof ResourceUrlProvider) { - initLookupPath((ResourceUrlProvider) value); + if (value instanceof ResourceUrlProvider urlProvider) { + initLookupPath(urlProvider); } } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JstlUtils.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JstlUtils.java index 84c7d1a3d3..25cb945b6a 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JstlUtils.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/JstlUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -132,8 +132,8 @@ public abstract class JstlUtils { HttpSession session = this.request.getSession(false); if (session != null) { Object lcObject = Config.get(session, Config.FMT_LOCALIZATION_CONTEXT); - if (lcObject instanceof LocalizationContext) { - ResourceBundle lcBundle = ((LocalizationContext) lcObject).getResourceBundle(); + if (lcObject instanceof LocalizationContext localizationContext) { + ResourceBundle lcBundle = localizationContext.getResourceBundle(); return new MessageSourceResourceBundle(this.messageSource, getLocale(), lcBundle); } } @@ -145,8 +145,8 @@ public abstract class JstlUtils { HttpSession session = this.request.getSession(false); if (session != null) { Object localeObject = Config.get(session, Config.FMT_LOCALE); - if (localeObject instanceof Locale) { - return (Locale) localeObject; + if (localeObject instanceof Locale locale) { + return locale; } } return RequestContextUtils.getLocale(this.request); 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 4167936b12..9b876f6e1a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -226,11 +226,11 @@ public class RequestContext { // Determine locale to use for this RequestContext. LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); - if (localeResolver instanceof LocaleContextResolver) { - LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request); + if (localeResolver instanceof LocaleContextResolver localeContextResolver) { + LocaleContext localeContext = localeContextResolver.resolveLocaleContext(request); locale = localeContext.getLocale(); - if (localeContext instanceof TimeZoneAwareLocaleContext) { - timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); + if (localeContext instanceof TimeZoneAwareLocaleContext timeZoneAwareLocaleContext) { + timeZone = timeZoneAwareLocaleContext.getTimeZone(); } } else if (localeResolver != null) { @@ -378,10 +378,10 @@ public class RequestContext { */ public void changeLocale(Locale locale, TimeZone timeZone) { LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(this.request); - if (!(localeResolver instanceof LocaleContextResolver)) { + if (!(localeResolver instanceof LocaleContextResolver localeContextResolver)) { throw new IllegalStateException("Cannot change locale context if no LocaleContextResolver configured"); } - ((LocaleContextResolver) localeResolver).setLocaleContext(this.request, this.response, + localeContextResolver.setLocaleContext(this.request, this.response, new SimpleTimeZoneAwareLocaleContext(locale, timeZone)); this.locale = locale; this.timeZone = timeZone; @@ -867,8 +867,8 @@ public class RequestContext { if (errors == null) { errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name); // Check old BindException prefix for backwards compatibility. - if (errors instanceof BindException) { - errors = ((BindException) errors).getBindingResult(); + if (errors instanceof BindException bindException) { + errors = bindException.getBindingResult(); } if (errors == null) { return null; @@ -879,8 +879,8 @@ public class RequestContext { errors = new EscapedErrors(errors); put = true; } - else if (!htmlEscape && errors instanceof EscapedErrors) { - errors = ((EscapedErrors) errors).getSource(); + else if (!htmlEscape && errors instanceof EscapedErrors escapedErrors) { + errors = escapedErrors.getSource(); put = true; } if (put) { @@ -945,7 +945,7 @@ public class RequestContext { localeObject = Config.get(servletContext, Config.FMT_LOCALE); } } - return (localeObject instanceof Locale ? (Locale) localeObject : null); + return (localeObject instanceof Locale locale ? locale : null); } @Nullable @@ -960,7 +960,7 @@ public class RequestContext { timeZoneObject = Config.get(servletContext, 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/tags/MessageTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/MessageTag.java index 94e7dc2d52..7262448727 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/MessageTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/MessageTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -357,14 +357,14 @@ public class MessageTag extends HtmlEscapingAwareTag implements ArgumentAware { */ @Nullable protected Object[] resolveArguments(@Nullable Object arguments) throws JspException { - if (arguments instanceof String) { - return StringUtils.delimitedListToStringArray((String) arguments, this.argumentSeparator); + if (arguments instanceof String string) { + return StringUtils.delimitedListToStringArray(string, this.argumentSeparator); } - else if (arguments instanceof Object[]) { - return (Object[]) arguments; + else if (arguments instanceof Object[] array) { + return array; } - else if (arguments instanceof Collection) { - return ((Collection) arguments).toArray(); + else if (arguments instanceof Collection collection) { + return collection.toArray(); } else if (arguments != null) { // Assume a single argument object. diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java index 5109247f4b..421a50e3d9 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -240,8 +240,8 @@ public class UrlTag extends HtmlEscapingAwareTag implements ParamAware { RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); ServletRequest request = this.pageContext.getRequest(); - if ((processor != null) && (request instanceof HttpServletRequest)) { - url = processor.processUrl((HttpServletRequest) request, url); + if ((processor != null) && (request instanceof HttpServletRequest httpServletRequest)) { + url = processor.processUrl(httpServletRequest, url); } if (this.var == null) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractDataBoundFormElementTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractDataBoundFormElementTag.java index b839a65034..fb017d822c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractDataBoundFormElementTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractDataBoundFormElementTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -243,8 +243,8 @@ public abstract class AbstractDataBoundFormElementTag extends AbstractFormTag im protected final String processFieldValue(@Nullable String name, String value, String type) { RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); ServletRequest request = this.pageContext.getRequest(); - if (processor != null && request instanceof HttpServletRequest) { - value = processor.processFormFieldValue((HttpServletRequest) request, name, value, type); + if (processor != null && request instanceof HttpServletRequest httpServletRequest) { + value = processor.processFormFieldValue(httpServletRequest, name, value, type); } return value; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractMultiCheckedElementTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractMultiCheckedElementTag.java index 175c9bb044..21981acb3c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractMultiCheckedElementTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractMultiCheckedElementTag.java @@ -223,7 +223,7 @@ public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElem writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i); } } - else if (itemsObject instanceof final Collection optionCollection) { + else if (itemsObject instanceof Collection optionCollection) { int itemIndex = 0; for (Iterator it = optionCollection.iterator(); it.hasNext(); itemIndex++) { Object item = it.next(); @@ -252,8 +252,8 @@ public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElem if (valueProperty != null) { renderValue = wrapper.getPropertyValue(valueProperty); } - else if (item instanceof Enum) { - renderValue = ((Enum) item).name(); + else if (item instanceof Enum enumValue) { + renderValue = enumValue.name(); } else { renderValue = item; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/CheckboxTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/CheckboxTag.java index 7f5518a657..4369ffe3ce 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/CheckboxTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/CheckboxTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -250,8 +250,8 @@ public class CheckboxTag extends AbstractSingleCheckedElementTag { if (Boolean.class == valueType || boolean.class == valueType) { // the concrete type may not be a Boolean - can be String - if (boundValue instanceof String) { - boundValue = Boolean.valueOf((String) boundValue); + if (boundValue instanceof String string) { + boundValue = Boolean.valueOf(string); } Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE); renderFromBoolean(booleanValue, tagWriter); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java index d4028073a1..b4178e69d2 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -652,8 +652,8 @@ public class FormTag extends AbstractHtmlElementTag { // shouldn't happen - if it does, proceed with requestUri as-is } ServletResponse response = this.pageContext.getResponse(); - if (response instanceof HttpServletResponse) { - requestUri = ((HttpServletResponse) response).encodeURL(requestUri); + if (response instanceof HttpServletResponse httpServletResponse) { + requestUri = httpServletResponse.encodeURL(requestUri); String queryString = getRequestContext().getQueryString(); if (StringUtils.hasText(queryString)) { requestUri += "?" + HtmlUtils.htmlEscape(queryString); @@ -676,8 +676,8 @@ public class FormTag extends AbstractHtmlElementTag { private String processAction(String action) { RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); ServletRequest request = this.pageContext.getRequest(); - if (processor != null && request instanceof HttpServletRequest) { - action = processor.processAction((HttpServletRequest) request, action, getHttpMethod()); + if (processor != null && request instanceof HttpServletRequest httpServletRequest) { + action = processor.processAction(httpServletRequest, action, getHttpMethod()); } return action; } @@ -690,8 +690,8 @@ public class FormTag extends AbstractHtmlElementTag { public int doEndTag() throws JspException { RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); ServletRequest request = this.pageContext.getRequest(); - if (processor != null && request instanceof HttpServletRequest) { - writeHiddenFields(processor.getExtraHiddenFields((HttpServletRequest) request)); + if (processor != null && request instanceof HttpServletRequest httpServletRequest) { + writeHiddenFields(processor.getExtraHiddenFields(httpServletRequest)); } Assert.state(this.tagWriter != null, "No TagWriter set"); this.tagWriter.endTag(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionWriter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionWriter.java index 433ac220ed..b8a02730d8 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionWriter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -139,7 +139,7 @@ class OptionWriter { else if (this.optionSource instanceof Map) { renderFromMap(tagWriter); } - else if (this.optionSource instanceof Class && ((Class) this.optionSource).isEnum()) { + else if (this.optionSource instanceof Class clazz && clazz.isEnum()) { renderFromEnum(tagWriter); } else { @@ -205,8 +205,8 @@ class OptionWriter { if (this.valueProperty != null) { value = wrapper.getPropertyValue(this.valueProperty); } - else if (item instanceof Enum) { - value = ((Enum) item).name(); + else if (item instanceof Enum enumValue) { + value = enumValue.name(); } else { value = item; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java index 9ae09a40c6..6cbbb19c41 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java @@ -461,8 +461,8 @@ public class RedirectView extends AbstractUrlBasedView implements SmartView { if (rawValue != null && rawValue.getClass().isArray()) { values = CollectionUtils.arrayToList(rawValue); } - else if (rawValue instanceof Collection) { - values = ((Collection) rawValue); + else if (rawValue instanceof Collection collection) { + values = collection; } else { values = Collections.singleton(rawValue); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java index 1a7defde9c..a7276242f4 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/UrlBasedViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -613,8 +613,8 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements ApplicationContext context = getApplicationContext(); if (context != null) { Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName); - if (initialized instanceof View) { - return (View) initialized; + if (initialized instanceof View initializedView) { + return initializedView; } } return view; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xml/MarshallingView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xml/MarshallingView.java index 65c6820265..b7047ae525 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xml/MarshallingView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xml/MarshallingView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -166,8 +166,8 @@ public class MarshallingView extends AbstractView { protected boolean isEligibleForMarshalling(String modelKey, Object value) { Assert.state(this.marshaller != null, "No Marshaller set"); Class classToCheck = value.getClass(); - if (value instanceof JAXBElement) { - classToCheck = ((JAXBElement) value).getDeclaredType(); + if (value instanceof JAXBElement jaxbElement) { + classToCheck = jaxbElement.getDeclaredType(); } return this.marshaller.supports(classToCheck); }