Apply "instanceof pattern matching" in remainder of spring-webmvc module

See gh-30067
This commit is contained in:
Sam Brannen
2023-03-07 18:23:15 +01:00
parent 9b811a01f6
commit ffe7ec4a99
46 changed files with 214 additions and 232 deletions

View File

@@ -812,8 +812,8 @@ public class DispatcherServlet extends FrameworkServlet {
@Deprecated @Deprecated
@Nullable @Nullable
public final org.springframework.ui.context.ThemeSource getThemeSource() { public final org.springframework.ui.context.ThemeSource getThemeSource() {
return (getWebApplicationContext() instanceof org.springframework.ui.context.ThemeSource ? return (getWebApplicationContext() instanceof org.springframework.ui.context.ThemeSource themeSource ?
(org.springframework.ui.context.ThemeSource) getWebApplicationContext() : null); themeSource : null);
} }
/** /**
@@ -1143,9 +1143,9 @@ public class DispatcherServlet extends FrameworkServlet {
boolean errorView = false; boolean errorView = false;
if (exception != null) { if (exception != null) {
if (exception instanceof ModelAndViewDefiningException) { if (exception instanceof ModelAndViewDefiningException mavDefiningException) {
logger.debug("ModelAndViewDefiningException encountered", exception); logger.debug("ModelAndViewDefiningException encountered", exception);
mv = ((ModelAndViewDefiningException) exception).getModelAndView(); mv = mavDefiningException.getModelAndView();
} }
else { else {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
@@ -1188,8 +1188,8 @@ public class DispatcherServlet extends FrameworkServlet {
@Override @Override
protected LocaleContext buildLocaleContext(final HttpServletRequest request) { protected LocaleContext buildLocaleContext(final HttpServletRequest request) {
LocaleResolver lr = this.localeResolver; LocaleResolver lr = this.localeResolver;
if (lr instanceof LocaleContextResolver) { if (lr instanceof LocaleContextResolver localeContextResolver) {
return ((LocaleContextResolver) lr).resolveLocaleContext(request); return localeContextResolver.resolveLocaleContext(request);
} }
else { else {
return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale()); return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale());

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -195,7 +195,7 @@ public class ModelAndView {
*/ */
@Nullable @Nullable
public String getViewName() { 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 @Nullable
public View getView() { public View getView() {
return (this.view instanceof View ? (View) this.view : null); return (this.view instanceof View v ? v : null);
} }
/** /**

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { private static boolean containsBeanInHierarchy(ParserContext context, String beanName) {
BeanDefinitionRegistry registry = context.getRegistry(); BeanDefinitionRegistry registry = context.getRegistry();
return (registry instanceof BeanFactory ? ((BeanFactory) registry).containsBean(beanName) : return (registry instanceof BeanFactory beanFactory ? beanFactory.containsBean(beanName) :
registry.containsBeanDefinition(beanName)); registry.containsBeanDefinition(beanName));
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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<Object> INTERCEPTOR_ORDER_COMPARATOR = private static final Comparator<Object> INTERCEPTOR_ORDER_COMPARATOR =
OrderComparator.INSTANCE.withSourceProvider(object -> { OrderComparator.INSTANCE.withSourceProvider(object -> {
if (object instanceof InterceptorRegistration) { if (object instanceof InterceptorRegistration interceptorRegistration) {
return (Ordered) ((InterceptorRegistration) object)::getOrder; return (Ordered) interceptorRegistration::getOrder;
} }
return null; return null;
}); });

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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; return result;
} }
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked", "rawtypes"})
public static AsyncServerResponse create(Object o, @Nullable Duration timeout) { public static AsyncServerResponse create(Object obj, @Nullable Duration timeout) {
Assert.notNull(o, "Argument to async must not be null"); Assert.notNull(obj, "Argument to async must not be null");
if (o instanceof CompletableFuture) { if (obj instanceof CompletableFuture futureResponse) {
CompletableFuture<ServerResponse> futureResponse = (CompletableFuture<ServerResponse>) o;
return new DefaultAsyncServerResponse(futureResponse, timeout); return new DefaultAsyncServerResponse(futureResponse, timeout);
} }
else if (reactiveStreamsPresent) { else if (reactiveStreamsPresent) {
ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance(); ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
ReactiveAdapter publisherAdapter = registry.getAdapter(o.getClass()); ReactiveAdapter publisherAdapter = registry.getAdapter(obj.getClass());
if (publisherAdapter != null) { if (publisherAdapter != null) {
Publisher<ServerResponse> publisher = publisherAdapter.toPublisher(o); Publisher<ServerResponse> publisher = publisherAdapter.toPublisher(obj);
ReactiveAdapter futureAdapter = registry.getAdapter(CompletableFuture.class); ReactiveAdapter futureAdapter = registry.getAdapter(CompletableFuture.class);
if (futureAdapter != null) { if (futureAdapter != null) {
CompletableFuture<ServerResponse> futureResponse = CompletableFuture<ServerResponse> 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());
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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); MediaType contentType = headers().contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) { if (messageConverter instanceof GenericHttpMessageConverter<?> genericMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter =
(GenericHttpMessageConverter<T>) messageConverter;
if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) { if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
return genericMessageConverter.read(bodyType, bodyClass, inputMessage); return (T) genericMessageConverter.read(bodyType, bodyClass, inputMessage);
} }
} }
if (messageConverter.canRead(bodyClass, contentType)) { if (messageConverter.canRead(bodyClass, contentType)) {

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { if (serverResponse != null) {
return serverResponse.writeTo(servletRequest, servletResponse, context); return serverResponse.writeTo(servletRequest, servletResponse, context);
} }
else if (t instanceof ServletException) { else if (t instanceof ServletException servletException) {
throw (ServletException) t; throw servletException;
} }
else if (t instanceof IOException) { else if (t instanceof IOException ioException ) {
throw (IOException) t; throw ioException;
} }
else { else {
throw new ServletException(t); throw new ServletException(t);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -112,8 +112,8 @@ public interface HandlerFilterFunction<T extends ServerResponse, R extends Serve
return (request, next) -> { return (request, next) -> {
try { try {
T t = next.handle(request); T t = next.handle(request);
if (t instanceof ErrorHandlingServerResponse) { if (t instanceof ErrorHandlingServerResponse response) {
((ErrorHandlingServerResponse) t).addErrorHandler(predicate, errorHandler); response.addErrorHandler(predicate, errorHandler);
} }
return t; return t;
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -125,8 +125,8 @@ class PathResourceLookupFunction implements Function<ServerRequest, Optional<Res
resourcePath = resource.getURL().toExternalForm(); resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(this.location.getURL().toString()); locationPath = StringUtils.cleanPath(this.location.getURL().toString());
} }
else if (resource instanceof ClassPathResource) { else if (resource instanceof ClassPathResource classPathResource) {
resourcePath = ((ClassPathResource) resource).getPath(); resourcePath = classPathResource.getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath()); locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
} }
else { else {

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -168,8 +168,8 @@ final class SseServerResponse extends AbstractServerResponse {
public void data(Object object) throws IOException { public void data(Object object) throws IOException {
Assert.notNull(object, "Object must not be null"); Assert.notNull(object, "Object must not be null");
if (object instanceof String) { if (object instanceof String text) {
writeString((String) object); writeString(text);
} }
else { else {
writeObject(object); writeObject(object);

View File

@@ -140,14 +140,14 @@ public class HandlerFunctionAdapter implements HandlerAdapter, Ordered {
String formatted = LogFormatUtils.formatValue(result, !traceOn); String formatted = LogFormatUtils.formatValue(result, !traceOn);
return "Resume with async result [" + formatted + "]"; return "Resume with async result [" + formatted + "]";
}); });
if (result instanceof ServerResponse) { if (result instanceof ServerResponse response) {
return (ServerResponse) result; return response;
} }
else if (result instanceof Exception) { else if (result instanceof Exception exception) {
throw (Exception) result; throw exception;
} }
else if (result instanceof Throwable) { else if (result instanceof Throwable throwable) {
throw new ServletException("Async processing failed", (Throwable) result); throw new ServletException("Async processing failed", throwable);
} }
else if (result == null) { else if (result == null) {
return null; return null;

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -70,7 +70,7 @@ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHan
protected final ModelAndView doResolveException( protected final ModelAndView doResolveException(
HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
HandlerMethod handlerMethod = (handler instanceof HandlerMethod ? (HandlerMethod) handler : null); HandlerMethod handlerMethod = (handler instanceof HandlerMethod hm ? hm : null);
return doResolveHandlerMethodException(request, response, handlerMethod, ex); return doResolveHandlerMethodException(request, response, handlerMethod, ex);
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -121,7 +121,7 @@ public class HandlerMappingIntrospector
public MatchableHandlerMapping getMatchableHandlerMapping(HttpServletRequest request) throws Exception { public MatchableHandlerMapping getMatchableHandlerMapping(HttpServletRequest request) throws Exception {
HttpServletRequest wrappedRequest = new AttributesPreservingRequest(request); HttpServletRequest wrappedRequest = new AttributesPreservingRequest(request);
return doWithMatchingMapping(wrappedRequest, false, (matchedMapping, executionChain) -> { return doWithMatchingMapping(wrappedRequest, false, (matchedMapping, executionChain) -> {
if (matchedMapping instanceof MatchableHandlerMapping) { if (matchedMapping instanceof MatchableHandlerMapping matchableHandlerMapping) {
PathPatternMatchableHandlerMapping mapping = this.pathPatternHandlerMappings.get(matchedMapping); PathPatternMatchableHandlerMapping mapping = this.pathPatternHandlerMappings.get(matchedMapping);
if (mapping != null) { if (mapping != null) {
RequestPath requestPath = ServletRequestPathUtils.getParsedRequestPath(wrappedRequest); RequestPath requestPath = ServletRequestPathUtils.getParsedRequestPath(wrappedRequest);
@@ -129,7 +129,7 @@ public class HandlerMappingIntrospector
} }
else { else {
String lookupPath = (String) wrappedRequest.getAttribute(UrlPathHelper.PATH_ATTRIBUTE); 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"); throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
@@ -142,12 +142,12 @@ public class HandlerMappingIntrospector
AttributesPreservingRequest wrappedRequest = new AttributesPreservingRequest(request); AttributesPreservingRequest wrappedRequest = new AttributesPreservingRequest(request);
return doWithMatchingMappingIgnoringException(wrappedRequest, (handlerMapping, executionChain) -> { return doWithMatchingMappingIgnoringException(wrappedRequest, (handlerMapping, executionChain) -> {
for (HandlerInterceptor interceptor : executionChain.getInterceptorList()) { for (HandlerInterceptor interceptor : executionChain.getInterceptorList()) {
if (interceptor instanceof CorsConfigurationSource) { if (interceptor instanceof CorsConfigurationSource ccs) {
return ((CorsConfigurationSource) interceptor).getCorsConfiguration(wrappedRequest); return ccs.getCorsConfiguration(wrappedRequest);
} }
} }
if (executionChain.getHandler() instanceof CorsConfigurationSource) { if (executionChain.getHandler() instanceof CorsConfigurationSource ccs) {
return ((CorsConfigurationSource) executionChain.getHandler()).getCorsConfiguration(wrappedRequest); return ccs.getCorsConfiguration(wrappedRequest);
} }
return null; return null;
}); });
@@ -246,8 +246,8 @@ public class HandlerMappingIntrospector
List<HandlerMapping> mappings) { List<HandlerMapping> mappings) {
return mappings.stream() return mappings.stream()
.filter(mapping -> mapping instanceof MatchableHandlerMapping) .filter(MatchableHandlerMapping.class::isInstance)
.map(mapping -> (MatchableHandlerMapping) mapping) .map(MatchableHandlerMapping.class::cast)
.filter(mapping -> mapping.getPatternParser() != null) .filter(mapping -> mapping.getPatternParser() != null)
.collect(Collectors.toMap(mapping -> mapping, PathPatternMatchableHandlerMapping::new)); .collect(Collectors.toMap(mapping -> mapping, PathPatternMatchableHandlerMapping::new));
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -107,13 +107,13 @@ public class SimpleServletPostProcessor implements
@Override @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Servlet) { if (bean instanceof Servlet servlet) {
ServletConfig config = this.servletConfig; ServletConfig config = this.servletConfig;
if (config == null || !this.useSharedServletConfig) { if (config == null || !this.useSharedServletConfig) {
config = new DelegatingServletConfig(beanName, this.servletContext); config = new DelegatingServletConfig(beanName, this.servletContext);
} }
try { try {
((Servlet) bean).init(config); servlet.init(config);
} }
catch (ServletException ex) { catch (ServletException ex) {
throw new BeanInitializationException("Servlet.init threw exception", ex); throw new BeanInitializationException("Servlet.init threw exception", ex);
@@ -124,8 +124,8 @@ public class SimpleServletPostProcessor implements
@Override @Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if (bean instanceof Servlet) { if (bean instanceof Servlet servlet) {
((Servlet) bean).destroy(); servlet.destroy();
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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; url = "/" + url;
} }
// Remove whitespace from handler bean name. // Remove whitespace from handler bean name.
if (handler instanceof String) { if (handler instanceof String handlerName) {
handler = ((String) handler).trim(); handler = handlerName.trim();
} }
registerHandler(url, handler); registerHandler(url, handler);
}); });

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -56,8 +56,8 @@ public class HttpRequestHandlerAdapter implements HandlerAdapter {
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public long getLastModified(HttpServletRequest request, Object handler) { public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) { if (handler instanceof LastModified lastModified) {
return ((LastModified) handler).getLastModified(request); return lastModified.getLastModified(request);
} }
return -1L; return -1L;
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -95,7 +95,7 @@ public class ParameterizableViewController extends AbstractController {
*/ */
@Nullable @Nullable
public View getView() { public View getView() {
return (this.view instanceof View ? (View) this.view : null); return (this.view instanceof View v ? v : null);
} }
/** /**

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -54,8 +54,8 @@ public class SimpleControllerHandlerAdapter implements HandlerAdapter {
@Override @Override
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public long getLastModified(HttpServletRequest request, Object handler) { public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) { if (handler instanceof LastModified lastModified) {
return ((LastModified) handler).getLastModified(request); return lastModified.getLastModified(request);
} }
return -1L; return -1L;
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
try { try {
if (ex instanceof ResponseStatusException) { if (ex instanceof ResponseStatusException rse) {
return resolveResponseStatusException((ResponseStatusException) ex, request, response, handler); return resolveResponseStatusException(rse, request, response, handler);
} }
ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class); ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
@@ -81,8 +81,8 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes
return resolveResponseStatus(status, request, response, handler, ex); return resolveResponseStatus(status, request, response, handler, ex);
} }
if (ex.getCause() instanceof Exception) { if (ex.getCause() instanceof Exception cause) {
return doResolveException(request, response, handler, (Exception) ex.getCause()); return doResolveException(request, response, handler, cause);
} }
} }
catch (Exception resolveEx) { catch (Exception resolveEx) {

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 @Override
public final boolean supports(Object handler) { public final boolean supports(Object handler) {
return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler)); return (handler instanceof HandlerMethod handlerMethod && supportsInternal(handlerMethod));
} }
/** /**

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -240,9 +240,8 @@ public final class RequestMappingInfo implements RequestCondition<RequestMapping
*/ */
public Set<String> getDirectPaths() { public Set<String> getDirectPaths() {
RequestCondition<?> condition = getActivePatternsCondition(); RequestCondition<?> condition = getActivePatternsCondition();
return (condition instanceof PathPatternsRequestCondition ? return (condition instanceof PathPatternsRequestCondition pprc ?
((PathPatternsRequestCondition) condition).getDirectPaths() : pprc.getDirectPaths() : ((PatternsRequestCondition) condition).getDirectPaths());
((PatternsRequestCondition) condition).getDirectPaths());
} }
/** /**
@@ -252,9 +251,8 @@ public final class RequestMappingInfo implements RequestCondition<RequestMapping
*/ */
public Set<String> getPatternValues() { public Set<String> getPatternValues() {
RequestCondition<?> condition = getActivePatternsCondition(); RequestCondition<?> condition = getActivePatternsCondition();
return (condition instanceof PathPatternsRequestCondition ? return (condition instanceof PathPatternsRequestCondition pprc ?
((PathPatternsRequestCondition) condition).getPatternValues() : pprc.getPatternValues() : ((PatternsRequestCondition) condition).getPatterns());
((PatternsRequestCondition) condition).getPatterns());
} }
/** /**

View File

@@ -141,8 +141,8 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe
super.handleMatch(info, lookupPath, request); super.handleMatch(info, lookupPath, request);
RequestCondition<?> condition = info.getActivePatternsCondition(); RequestCondition<?> condition = info.getActivePatternsCondition();
if (condition instanceof PathPatternsRequestCondition) { if (condition instanceof PathPatternsRequestCondition pprc) {
extractMatchDetails((PathPatternsRequestCondition) condition, lookupPath, request); extractMatchDetails(pprc, lookupPath, request);
} }
else { else {
extractMatchDetails((PatternsRequestCondition) condition, lookupPath, request); extractMatchDetails((PatternsRequestCondition) condition, lookupPath, request);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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. * additional serialization instructions) or simply cast it if already wrapped.
*/ */
protected MappingJacksonValue getOrCreateContainer(Object body) { protected MappingJacksonValue getOrCreateContainer(Object body) {
return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body)); return (body instanceof MappingJacksonValue mjv ? mjv : new MappingJacksonValue(body));
} }
/** /**

View File

@@ -138,13 +138,13 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements
* @throws IOException if the reading from the request fails * @throws IOException if the reading from the request fails
* @throws HttpMediaTypeNotSupportedException if no suitable message converter is found * @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
*/ */
@SuppressWarnings("unchecked")
@Nullable @Nullable
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter, protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException { Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
Class<?> contextClass = parameter.getContainingClass(); Class<?> contextClass = parameter.getContainingClass();
Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null); Class<T> targetClass = (targetType instanceof Class clazz ? clazz : null);
if (targetClass == null) { if (targetClass == null) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
targetClass = (Class<T>) resolvableType.resolve(); targetClass = (Class<T>) resolvableType.resolve();
@@ -164,7 +164,7 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements
contentType = MediaType.APPLICATION_OCTET_STREAM; 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; Object body = NO_VALUE;
EmptyBodyCheckingHttpInputMessage message = null; EmptyBodyCheckingHttpInputMessage message = null;
@@ -174,7 +174,7 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements
for (HttpMessageConverter<?> converter : this.messageConverters) { for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass(); Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
GenericHttpMessageConverter<?> genericConverter = GenericHttpMessageConverter<?> genericConverter =
(converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null); (converter instanceof GenericHttpMessageConverter ghmc ? ghmc : null);
if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) : if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
(targetClass != null && converter.canRead(targetClass, contentType))) { (targetClass != null && converter.canRead(targetClass, contentType))) {
if (message.hasBody()) { if (message.hasBody()) {
@@ -290,8 +290,8 @@ public abstract class AbstractMessageConverterMethodArgumentResolver implements
@Nullable @Nullable
protected Object adaptArgumentIfNecessary(@Nullable Object arg, MethodParameter parameter) { protected Object adaptArgumentIfNecessary(@Nullable Object arg, MethodParameter parameter) {
if (parameter.getParameterType() == Optional.class) { if (parameter.getParameterType() == Optional.class) {
if (arg == null || (arg instanceof Collection && ((Collection<?>) arg).isEmpty()) || if (arg == null || (arg instanceof Collection<?> collection && collection.isEmpty()) ||
(arg instanceof Object[] && ((Object[]) arg).length == 0)) { (arg instanceof Object[] array && array.length == 0)) {
return Optional.empty(); return Optional.empty();
} }
else { else {

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { if (selectedMediaType != null) {
selectedMediaType = selectedMediaType.removeQualityValue(); selectedMediaType = selectedMediaType.removeQualityValue();
for (HttpMessageConverter<?> converter : this.messageConverters) { for (HttpMessageConverter<?> converter : this.messageConverters) {
GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ? GenericHttpMessageConverter genericConverter =
(GenericHttpMessageConverter<?>) converter : null); (converter instanceof GenericHttpMessageConverter ghmc ? ghmc : null);
if (genericConverter != null ? if (genericConverter != null ?
((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) : ((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) :
converter.canWrite(valueType, selectedMediaType)) { converter.canWrite(valueType, selectedMediaType)) {
@@ -383,8 +383,8 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe
} }
Set<MediaType> result = new LinkedHashSet<>(); Set<MediaType> result = new LinkedHashSet<>();
for (HttpMessageConverter<?> converter : this.messageConverters) { for (HttpMessageConverter<?> converter : this.messageConverters) {
if (converter instanceof GenericHttpMessageConverter && targetType != null) { if (converter instanceof GenericHttpMessageConverter<?> ghmc && targetType != null) {
if (((GenericHttpMessageConverter<?>) converter).canWrite(targetType, valueClass, null)) { if (ghmc.canWrite(targetType, valueClass, null)) {
result.addAll(converter.getSupportedMediaTypes(valueClass)); result.addAll(converter.getSupportedMediaTypes(valueClass));
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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()) { if (!mavContainer.isViewReference()) {
mav.setView((View) mavContainer.getView()); mav.setView((View) mavContainer.getView());
} }
if (model instanceof RedirectAttributes) { if (model instanceof RedirectAttributes redirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes(); Map<String, ?> flashAttributes = redirectAttributes.getFlashAttributes();
RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes); RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
} }
return mav; return mav;

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -94,7 +94,7 @@ public class ModelAndViewMethodReturnValueHandler implements HandlerMethodReturn
else { else {
View view = mav.getView(); View view = mav.getView();
mavContainer.setView(view); mavContainer.setView(view);
if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { if (view instanceof SmartView smartView && smartView.isRedirectView()) {
mavContainer.setRedirectModelScenario(true); mavContainer.setRedirectModelScenario(true);
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -139,8 +139,8 @@ public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethod
@Nullable @Nullable
protected String formatUriValue(@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, Object value) { protected String formatUriValue(@Nullable ConversionService cs, @Nullable TypeDescriptor sourceType, Object value) {
if (value instanceof String) { if (value instanceof String string) {
return (String) value; return string;
} }
else if (cs != null) { else if (cs != null) {
return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR); return (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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"); Assert.state(request != null, "No ServletRequest");
ResponseBodyEmitter emitter; ResponseBodyEmitter emitter;
if (returnValue instanceof ResponseBodyEmitter) { if (returnValue instanceof ResponseBodyEmitter responseBodyEmitter) {
emitter = (ResponseBodyEmitter) returnValue; emitter = responseBodyEmitter;
} }
else { else {
emitter = this.reactiveHandler.handleValue(returnValue, returnType, mavContainer, webRequest); emitter = this.reactiveHandler.handleValue(returnValue, returnType, mavContainer, webRequest);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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.InvocableHandlerMethod;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.View; 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 * 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) { public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) {
super((Callable<Object>) () -> { super((Callable<Object>) () -> {
if (result instanceof Exception) { if (result instanceof Exception exception) {
throw (Exception) result; throw exception;
} }
else if (result instanceof Throwable) { else if (result instanceof Throwable throwable) {
throw new ServletException("Async processing failed: " + result, (Throwable) result); throw new ServletException("Async processing failed: " + result, throwable);
} }
return result; return result;
}, CALLABLE_METHOD); }, CALLABLE_METHOD);
@@ -281,8 +282,8 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod {
public ConcurrentResultMethodParameter(Object returnValue) { public ConcurrentResultMethodParameter(Object returnValue) {
super(-1); super(-1);
this.returnValue = returnValue; this.returnValue = returnValue;
this.returnType = (returnValue instanceof ReactiveTypeHandler.CollectedValuesList ? this.returnType = (returnValue instanceof CollectedValuesList cvList ?
((ReactiveTypeHandler.CollectedValuesList) returnValue).getReturnType() : cvList.getReturnType() :
KotlinDetector.isSuspendingFunction(super.getMethod()) ? KotlinDetector.isSuspendingFunction(super.getMethod()) ?
ResolvableType.forMethodParameter(getReturnType()) : ResolvableType.forMethodParameter(getReturnType()) :
ResolvableType.forType(super.getGenericParameterType()).getGeneric()); ResolvableType.forType(super.getGenericParameterType()).getGeneric());
@@ -316,7 +317,7 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod {
// even if actual return type is ResponseEntity<Flux<T>> // even if actual return type is ResponseEntity<Flux<T>>
return (super.hasMethodAnnotation(annotationType) || return (super.hasMethodAnnotation(annotationType) ||
(annotationType == ResponseBody.class && (annotationType == ResponseBody.class &&
this.returnValue instanceof ReactiveTypeHandler.CollectedValuesList)); this.returnValue instanceof CollectedValuesList));
} }
@Override @Override

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { if (returnValue instanceof View view) {
mavContainer.setView(view); mavContainer.setView(view);
if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { if (view instanceof SmartView smartView && smartView.isRedirectView()) {
mavContainer.setRedirectModelScenario(true); mavContainer.setRedirectModelScenario(true);
} }
} }

View File

@@ -169,73 +169,59 @@ public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionRes
try { try {
// ErrorResponse exceptions that expose HTTP response details // ErrorResponse exceptions that expose HTTP response details
if (ex instanceof ErrorResponse) { if (ex instanceof ErrorResponse errorResponse) {
ModelAndView mav = null; ModelAndView mav = null;
if (ex instanceof HttpRequestMethodNotSupportedException) { if (ex instanceof HttpRequestMethodNotSupportedException theEx) {
mav = handleHttpRequestMethodNotSupported( mav = handleHttpRequestMethodNotSupported(theEx, request, response, handler);
(HttpRequestMethodNotSupportedException) ex, request, response, handler);
} }
else if (ex instanceof HttpMediaTypeNotSupportedException) { else if (ex instanceof HttpMediaTypeNotSupportedException theEx) {
mav = handleHttpMediaTypeNotSupported( mav = handleHttpMediaTypeNotSupported(theEx, request, response, handler);
(HttpMediaTypeNotSupportedException) ex, request, response, handler);
} }
else if (ex instanceof HttpMediaTypeNotAcceptableException) { else if (ex instanceof HttpMediaTypeNotAcceptableException theEx) {
mav = handleHttpMediaTypeNotAcceptable( mav = handleHttpMediaTypeNotAcceptable(theEx, request, response, handler);
(HttpMediaTypeNotAcceptableException) ex, request, response, handler);
} }
else if (ex instanceof MissingPathVariableException) { else if (ex instanceof MissingPathVariableException theEx) {
mav = handleMissingPathVariable( mav = handleMissingPathVariable(theEx, request, response, handler);
(MissingPathVariableException) ex, request, response, handler);
} }
else if (ex instanceof MissingServletRequestParameterException) { else if (ex instanceof MissingServletRequestParameterException theEx) {
mav = handleMissingServletRequestParameter( mav = handleMissingServletRequestParameter(theEx, request, response, handler);
(MissingServletRequestParameterException) ex, request, response, handler);
} }
else if (ex instanceof MissingServletRequestPartException) { else if (ex instanceof MissingServletRequestPartException theEx) {
mav = handleMissingServletRequestPartException( mav = handleMissingServletRequestPartException(theEx, request, response, handler);
(MissingServletRequestPartException) ex, request, response, handler);
} }
else if (ex instanceof ServletRequestBindingException) { else if (ex instanceof ServletRequestBindingException theEx) {
mav = handleServletRequestBindingException( mav = handleServletRequestBindingException(theEx, request, response, handler);
(ServletRequestBindingException) ex, request, response, handler);
} }
else if (ex instanceof MethodArgumentNotValidException) { else if (ex instanceof MethodArgumentNotValidException theEx) {
mav = handleMethodArgumentNotValidException( mav = handleMethodArgumentNotValidException(theEx, request, response, handler);
(MethodArgumentNotValidException) ex, request, response, handler);
} }
else if (ex instanceof NoHandlerFoundException) { else if (ex instanceof NoHandlerFoundException theEx) {
mav = handleNoHandlerFoundException( mav = handleNoHandlerFoundException(theEx, request, response, handler);
(NoHandlerFoundException) ex, request, response, handler);
} }
else if (ex instanceof AsyncRequestTimeoutException) { else if (ex instanceof AsyncRequestTimeoutException theEx) {
mav = handleAsyncRequestTimeoutException( mav = handleAsyncRequestTimeoutException(theEx, request, response, handler);
(AsyncRequestTimeoutException) ex, request, response, handler);
} }
return (mav != null ? mav : return (mav != null ? mav :
handleErrorResponse((ErrorResponse) ex, request, response, handler)); handleErrorResponse(errorResponse, request, response, handler));
} }
// Other, lower level exceptions // Other, lower level exceptions
if (ex instanceof ConversionNotSupportedException) { if (ex instanceof ConversionNotSupportedException theEx) {
return handleConversionNotSupported( return handleConversionNotSupported(theEx, request, response, handler);
(ConversionNotSupportedException) ex, request, response, handler);
} }
else if (ex instanceof TypeMismatchException) { else if (ex instanceof TypeMismatchException theEx) {
return handleTypeMismatch( return handleTypeMismatch(theEx, request, response, handler);
(TypeMismatchException) ex, request, response, handler);
} }
else if (ex instanceof HttpMessageNotReadableException) { else if (ex instanceof HttpMessageNotReadableException theEx) {
return handleHttpMessageNotReadable( return handleHttpMessageNotReadable(theEx, request, response, handler);
(HttpMessageNotReadableException) ex, request, response, handler);
} }
else if (ex instanceof HttpMessageNotWritableException) { else if (ex instanceof HttpMessageNotWritableException theEx) {
return handleHttpMessageNotWritable( return handleHttpMessageNotWritable(theEx, request, response, handler);
(HttpMessageNotWritableException) ex, request, response, handler);
} }
else if (ex instanceof BindException) { else if (ex instanceof BindException theEx) {
return handleBindException((BindException) ex, request, response, handler); return handleBindException(theEx, request, response, handler);
} }
} }
catch (Exception handlerEx) { catch (Exception handlerEx) {

View File

@@ -285,8 +285,8 @@ public class EncodedResourceResolver extends AbstractResourceResolver {
@Override @Override
public HttpHeaders getResponseHeaders() { public HttpHeaders getResponseHeaders() {
HttpHeaders headers; HttpHeaders headers;
if (this.original instanceof HttpResource) { if (this.original instanceof HttpResource httpResource) {
headers = ((HttpResource) this.original).getResponseHeaders(); headers = httpResource.getResponseHeaders();
} }
else { else {
headers = new HttpHeaders(); headers = new HttpHeaders();

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { public void setAttribute(String name, Object value) {
super.setAttribute(name, value); super.setAttribute(name, value);
if (ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR.equals(name)) { if (ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR.equals(name)) {
if (value instanceof ResourceUrlProvider) { if (value instanceof ResourceUrlProvider urlProvider) {
initLookupPath((ResourceUrlProvider) value); initLookupPath(urlProvider);
} }
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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); HttpSession session = this.request.getSession(false);
if (session != null) { if (session != null) {
Object lcObject = Config.get(session, Config.FMT_LOCALIZATION_CONTEXT); Object lcObject = Config.get(session, Config.FMT_LOCALIZATION_CONTEXT);
if (lcObject instanceof LocalizationContext) { if (lcObject instanceof LocalizationContext localizationContext) {
ResourceBundle lcBundle = ((LocalizationContext) lcObject).getResourceBundle(); ResourceBundle lcBundle = localizationContext.getResourceBundle();
return new MessageSourceResourceBundle(this.messageSource, getLocale(), lcBundle); return new MessageSourceResourceBundle(this.messageSource, getLocale(), lcBundle);
} }
} }
@@ -145,8 +145,8 @@ public abstract class JstlUtils {
HttpSession session = this.request.getSession(false); HttpSession session = this.request.getSession(false);
if (session != null) { if (session != null) {
Object localeObject = Config.get(session, Config.FMT_LOCALE); Object localeObject = Config.get(session, Config.FMT_LOCALE);
if (localeObject instanceof Locale) { if (localeObject instanceof Locale locale) {
return (Locale) localeObject; return locale;
} }
} }
return RequestContextUtils.getLocale(this.request); return RequestContextUtils.getLocale(this.request);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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. // Determine locale to use for this RequestContext.
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver instanceof LocaleContextResolver) { if (localeResolver instanceof LocaleContextResolver localeContextResolver) {
LocaleContext localeContext = ((LocaleContextResolver) localeResolver).resolveLocaleContext(request); LocaleContext localeContext = localeContextResolver.resolveLocaleContext(request);
locale = localeContext.getLocale(); locale = localeContext.getLocale();
if (localeContext instanceof TimeZoneAwareLocaleContext) { if (localeContext instanceof TimeZoneAwareLocaleContext timeZoneAwareLocaleContext) {
timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone(); timeZone = timeZoneAwareLocaleContext.getTimeZone();
} }
} }
else if (localeResolver != null) { else if (localeResolver != null) {
@@ -378,10 +378,10 @@ public class RequestContext {
*/ */
public void changeLocale(Locale locale, TimeZone timeZone) { public void changeLocale(Locale locale, TimeZone timeZone) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(this.request); 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"); 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)); new SimpleTimeZoneAwareLocaleContext(locale, timeZone));
this.locale = locale; this.locale = locale;
this.timeZone = timeZone; this.timeZone = timeZone;
@@ -867,8 +867,8 @@ public class RequestContext {
if (errors == null) { if (errors == null) {
errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name); errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name);
// Check old BindException prefix for backwards compatibility. // Check old BindException prefix for backwards compatibility.
if (errors instanceof BindException) { if (errors instanceof BindException bindException) {
errors = ((BindException) errors).getBindingResult(); errors = bindException.getBindingResult();
} }
if (errors == null) { if (errors == null) {
return null; return null;
@@ -879,8 +879,8 @@ public class RequestContext {
errors = new EscapedErrors(errors); errors = new EscapedErrors(errors);
put = true; put = true;
} }
else if (!htmlEscape && errors instanceof EscapedErrors) { else if (!htmlEscape && errors instanceof EscapedErrors escapedErrors) {
errors = ((EscapedErrors) errors).getSource(); errors = escapedErrors.getSource();
put = true; put = true;
} }
if (put) { if (put) {
@@ -945,7 +945,7 @@ public class RequestContext {
localeObject = Config.get(servletContext, Config.FMT_LOCALE); localeObject = Config.get(servletContext, Config.FMT_LOCALE);
} }
} }
return (localeObject instanceof Locale ? (Locale) localeObject : null); return (localeObject instanceof Locale locale ? locale : null);
} }
@Nullable @Nullable
@@ -960,7 +960,7 @@ public class RequestContext {
timeZoneObject = Config.get(servletContext, Config.FMT_TIME_ZONE); timeZoneObject = Config.get(servletContext, Config.FMT_TIME_ZONE);
} }
} }
return (timeZoneObject instanceof TimeZone ? (TimeZone) timeZoneObject : null); return (timeZoneObject instanceof TimeZone timeZone ? timeZone : null);
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 @Nullable
protected Object[] resolveArguments(@Nullable Object arguments) throws JspException { protected Object[] resolveArguments(@Nullable Object arguments) throws JspException {
if (arguments instanceof String) { if (arguments instanceof String string) {
return StringUtils.delimitedListToStringArray((String) arguments, this.argumentSeparator); return StringUtils.delimitedListToStringArray(string, this.argumentSeparator);
} }
else if (arguments instanceof Object[]) { else if (arguments instanceof Object[] array) {
return (Object[]) arguments; return array;
} }
else if (arguments instanceof Collection) { else if (arguments instanceof Collection<?> collection) {
return ((Collection<?>) arguments).toArray(); return collection.toArray();
} }
else if (arguments != null) { else if (arguments != null) {
// Assume a single argument object. // Assume a single argument object.

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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(); RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest(); ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) { if ((processor != null) && (request instanceof HttpServletRequest httpServletRequest)) {
url = processor.processUrl((HttpServletRequest) request, url); url = processor.processUrl(httpServletRequest, url);
} }
if (this.var == null) { if (this.var == null) {

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { protected final String processFieldValue(@Nullable String name, String value, String type) {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest(); ServletRequest request = this.pageContext.getRequest();
if (processor != null && request instanceof HttpServletRequest) { if (processor != null && request instanceof HttpServletRequest httpServletRequest) {
value = processor.processFormFieldValue((HttpServletRequest) request, name, value, type); value = processor.processFormFieldValue(httpServletRequest, name, value, type);
} }
return value; return value;
} }

View File

@@ -223,7 +223,7 @@ public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElem
writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i); writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i);
} }
} }
else if (itemsObject instanceof final Collection<?> optionCollection) { else if (itemsObject instanceof Collection<?> optionCollection) {
int itemIndex = 0; int itemIndex = 0;
for (Iterator<?> it = optionCollection.iterator(); it.hasNext(); itemIndex++) { for (Iterator<?> it = optionCollection.iterator(); it.hasNext(); itemIndex++) {
Object item = it.next(); Object item = it.next();
@@ -252,8 +252,8 @@ public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElem
if (valueProperty != null) { if (valueProperty != null) {
renderValue = wrapper.getPropertyValue(valueProperty); renderValue = wrapper.getPropertyValue(valueProperty);
} }
else if (item instanceof Enum) { else if (item instanceof Enum<?> enumValue) {
renderValue = ((Enum<?>) item).name(); renderValue = enumValue.name();
} }
else { else {
renderValue = item; renderValue = item;

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { if (Boolean.class == valueType || boolean.class == valueType) {
// the concrete type may not be a Boolean - can be String // the concrete type may not be a Boolean - can be String
if (boundValue instanceof String) { if (boundValue instanceof String string) {
boundValue = Boolean.valueOf((String) boundValue); boundValue = Boolean.valueOf(string);
} }
Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE); Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE);
renderFromBoolean(booleanValue, tagWriter); renderFromBoolean(booleanValue, tagWriter);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // shouldn't happen - if it does, proceed with requestUri as-is
} }
ServletResponse response = this.pageContext.getResponse(); ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) { if (response instanceof HttpServletResponse httpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri); requestUri = httpServletResponse.encodeURL(requestUri);
String queryString = getRequestContext().getQueryString(); String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) { if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString); requestUri += "?" + HtmlUtils.htmlEscape(queryString);
@@ -676,8 +676,8 @@ public class FormTag extends AbstractHtmlElementTag {
private String processAction(String action) { private String processAction(String action) {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest(); ServletRequest request = this.pageContext.getRequest();
if (processor != null && request instanceof HttpServletRequest) { if (processor != null && request instanceof HttpServletRequest httpServletRequest) {
action = processor.processAction((HttpServletRequest) request, action, getHttpMethod()); action = processor.processAction(httpServletRequest, action, getHttpMethod());
} }
return action; return action;
} }
@@ -690,8 +690,8 @@ public class FormTag extends AbstractHtmlElementTag {
public int doEndTag() throws JspException { public int doEndTag() throws JspException {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest(); ServletRequest request = this.pageContext.getRequest();
if (processor != null && request instanceof HttpServletRequest) { if (processor != null && request instanceof HttpServletRequest httpServletRequest) {
writeHiddenFields(processor.getExtraHiddenFields((HttpServletRequest) request)); writeHiddenFields(processor.getExtraHiddenFields(httpServletRequest));
} }
Assert.state(this.tagWriter != null, "No TagWriter set"); Assert.state(this.tagWriter != null, "No TagWriter set");
this.tagWriter.endTag(); this.tagWriter.endTag();

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { else if (this.optionSource instanceof Map) {
renderFromMap(tagWriter); renderFromMap(tagWriter);
} }
else if (this.optionSource instanceof Class && ((Class<?>) this.optionSource).isEnum()) { else if (this.optionSource instanceof Class<?> clazz && clazz.isEnum()) {
renderFromEnum(tagWriter); renderFromEnum(tagWriter);
} }
else { else {
@@ -205,8 +205,8 @@ class OptionWriter {
if (this.valueProperty != null) { if (this.valueProperty != null) {
value = wrapper.getPropertyValue(this.valueProperty); value = wrapper.getPropertyValue(this.valueProperty);
} }
else if (item instanceof Enum) { else if (item instanceof Enum<?> enumValue) {
value = ((Enum<?>) item).name(); value = enumValue.name();
} }
else { else {
value = item; value = item;

View File

@@ -461,8 +461,8 @@ public class RedirectView extends AbstractUrlBasedView implements SmartView {
if (rawValue != null && rawValue.getClass().isArray()) { if (rawValue != null && rawValue.getClass().isArray()) {
values = CollectionUtils.arrayToList(rawValue); values = CollectionUtils.arrayToList(rawValue);
} }
else if (rawValue instanceof Collection) { else if (rawValue instanceof Collection<?> collection) {
values = ((Collection<?>) rawValue); values = collection;
} }
else { else {
values = Collections.singleton(rawValue); values = Collections.singleton(rawValue);

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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(); ApplicationContext context = getApplicationContext();
if (context != null) { if (context != null) {
Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName); Object initialized = context.getAutowireCapableBeanFactory().initializeBean(view, viewName);
if (initialized instanceof View) { if (initialized instanceof View initializedView) {
return (View) initialized; return initializedView;
} }
} }
return view; return view;

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { protected boolean isEligibleForMarshalling(String modelKey, Object value) {
Assert.state(this.marshaller != null, "No Marshaller set"); Assert.state(this.marshaller != null, "No Marshaller set");
Class<?> classToCheck = value.getClass(); Class<?> classToCheck = value.getClass();
if (value instanceof JAXBElement) { if (value instanceof JAXBElement<?> jaxbElement) {
classToCheck = ((JAXBElement<?>) value).getDeclaredType(); classToCheck = jaxbElement.getDeclaredType();
} }
return this.marshaller.supports(classToCheck); return this.marshaller.supports(classToCheck);
} }