Apply "instanceof pattern matching" in spring-webmvc

This commit also applies additional clean-up tasks such as the following.

- final fields
- diamond operator (<>) for anonymous inner classes
- try with resources
- multi-catch

This has only been applied to `src/main/java`.
This commit is contained in:
Sam Brannen 2021-10-17 18:49:02 +02:00
parent 8135ae6d38
commit 1f248b34f6
36 changed files with 185 additions and 228 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -165,10 +165,9 @@ public final class FlashMap extends HashMap<String, Object> implements Comparabl
if (this == other) {
return true;
}
if (!(other instanceof FlashMap)) {
if (!(other instanceof FlashMap otherFlashMap)) {
return false;
}
FlashMap otherFlashMap = (FlashMap) other;
return (super.equals(otherFlashMap) &&
ObjectUtils.nullSafeEquals(this.targetRequestPath, otherFlashMap.targetRequestPath) &&
this.targetRequestParams.equals(otherFlashMap.targetRequestParams));

View File

@ -507,8 +507,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext) {
this.webApplicationContext = (WebApplicationContext) applicationContext;
if (this.webApplicationContext == null && applicationContext instanceof WebApplicationContext wac) {
this.webApplicationContext = wac;
this.webApplicationContextInjected = true;
}
}
@ -565,18 +565,15 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
if (wac instanceof ConfigurableWebApplicationContext cwac && !cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
if (wac == null) {
@ -693,8 +690,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
if (env instanceof ConfigurableWebEnvironment cwe) {
cwe.initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
@ -824,10 +821,10 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic
*/
public void refresh() {
WebApplicationContext wac = getWebApplicationContext();
if (!(wac instanceof ConfigurableApplicationContext)) {
if (!(wac instanceof ConfigurableApplicationContext cac)) {
throw new IllegalStateException("WebApplicationContext does not support refresh: " + wac);
}
((ConfigurableApplicationContext) wac).refresh();
cac.refresh();
}
/**
@ -862,8 +859,8 @@ public abstract class FrameworkServlet extends HttpServletBean implements Applic
public void destroy() {
getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'");
// Only call close() on WebApplicationContext if locally managed...
if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
((ConfigurableApplicationContext) this.webApplicationContext).close();
if (!this.webApplicationContextInjected && this.webApplicationContext instanceof ConfigurableApplicationContext cac) {
cac.close();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -74,8 +74,7 @@ public class HandlerExecutionChain {
* @since 5.3
*/
public HandlerExecutionChain(Object handler, List<HandlerInterceptor> interceptorList) {
if (handler instanceof HandlerExecutionChain) {
HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
if (handler instanceof HandlerExecutionChain originalChain) {
this.handler = originalChain.getHandler();
this.interceptorList.addAll(originalChain.interceptorList);
}
@ -188,9 +187,8 @@ public class HandlerExecutionChain {
void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) {
for (int i = this.interceptorList.size() - 1; i >= 0; i--) {
HandlerInterceptor interceptor = this.interceptorList.get(i);
if (interceptor instanceof AsyncHandlerInterceptor) {
if (interceptor instanceof AsyncHandlerInterceptor asyncInterceptor) {
try {
AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) interceptor;
asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler);
}
catch (Throwable ex) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -514,8 +514,7 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
ManagedList<Object> result = new ManagedList<>();
for (Object object : list) {
if (object instanceof BeanDefinitionHolder) {
BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
if (object instanceof BeanDefinitionHolder beanDef) {
String className = beanDef.getBeanDefinition().getBeanClassName();
Assert.notNull(className, "No resolver class");
Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -39,7 +39,7 @@ import org.springframework.web.util.pattern.PathPattern;
public class ViewControllerRegistry {
@Nullable
private ApplicationContext applicationContext;
private final ApplicationContext applicationContext;
private final List<ViewControllerRegistration> registrations = new ArrayList<>(4);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -53,10 +53,10 @@ import org.springframework.web.servlet.view.script.ScriptTemplateViewResolver;
public class ViewResolverRegistry {
@Nullable
private ContentNegotiationManager contentNegotiationManager;
private final ContentNegotiationManager contentNegotiationManager;
@Nullable
private ApplicationContext applicationContext;
private final ApplicationContext applicationContext;
@Nullable
private ContentNegotiatingViewResolver contentNegotiatingResolver;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -69,8 +69,7 @@ class ChangePathPatternParserVisitor implements RouterFunctions.Visitor {
}
private void changeParser(RequestPredicate predicate) {
if (predicate instanceof Target) {
Target target = (Target) predicate;
if (predicate instanceof Target target) {
target.changeParser(this.parser);
}
}

View File

@ -202,8 +202,7 @@ final class DefaultEntityResponseBuilder<T> implements EntityResponse.Builder<T>
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public EntityResponse<T> build() {
if (this.entity instanceof CompletionStage) {
CompletionStage completionStage = (CompletionStage) this.entity;
if (this.entity instanceof CompletionStage completionStage) {
return new CompletionStageEntityResponse(this.status, this.headers, this.cookies,
completionStage, this.entityType);
}
@ -264,7 +263,7 @@ final class DefaultEntityResponseBuilder<T> implements EntityResponse.Builder<T>
return null;
}
@SuppressWarnings({ "unchecked", "resource" })
@SuppressWarnings({ "unchecked", "resource", "rawtypes" })
protected void writeEntityWithMessageConverters(Object entity, HttpServletRequest request,
HttpServletResponse response, ServerResponse.Context context)
throws ServletException, IOException {
@ -294,16 +293,14 @@ final class DefaultEntityResponseBuilder<T> implements EntityResponse.Builder<T>
}
for (HttpMessageConverter<?> messageConverter : context.messageConverters()) {
if (messageConverter instanceof GenericHttpMessageConverter<?>) {
GenericHttpMessageConverter<Object> genericMessageConverter =
(GenericHttpMessageConverter<Object>) messageConverter;
if (messageConverter instanceof GenericHttpMessageConverter genericMessageConverter) {
if (genericMessageConverter.canWrite(entityType, entityClass, contentType)) {
genericMessageConverter.write(entity, entityType, contentType, serverResponse);
return;
}
}
if (messageConverter.canWrite(entityClass, contentType)) {
((HttpMessageConverter<Object>)messageConverter).write(entity, contentType, serverResponse);
((HttpMessageConverter<Object>) messageConverter).write(entity, contentType, serverResponse);
return;
}
}

View File

@ -70,6 +70,7 @@ import org.springframework.web.util.UriBuilder;
* {@code ServerRequest} implementation based on a {@link HttpServletRequest}.
*
* @author Arjen Poutsma
* @author Sam Brannen
* @since 5.2
*/
class DefaultServerRequest implements ServerRequest {
@ -171,14 +172,12 @@ class DefaultServerRequest implements ServerRequest {
}
static Class<?> bodyClass(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
if (type instanceof Class<?> clazz) {
return clazz;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
if (parameterizedType.getRawType() instanceof Class) {
return (Class<?>) parameterizedType.getRawType();
}
if (type instanceof ParameterizedType parameterizedType &&
parameterizedType.getRawType() instanceof Class<?> rawType) {
return rawType;
}
return Object.class;
}
@ -188,11 +187,9 @@ class DefaultServerRequest implements ServerRequest {
MediaType contentType = this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<T> genericMessageConverter =
(GenericHttpMessageConverter<T>) messageConverter;
if (messageConverter instanceof GenericHttpMessageConverter<?> genericMessageConverter) {
if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
return (T) genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
}
}
if (messageConverter.canRead(bodyClass, contentType)) {

View File

@ -65,6 +65,7 @@ import org.springframework.web.util.pattern.PathPatternParser;
* request matching operations, such as matching based on path, HTTP method, etc.
*
* @author Arjen Poutsma
* @author Sam Brannen
* @since 5.2
*/
public abstract class RequestPredicates {
@ -792,11 +793,11 @@ public abstract class RequestPredicates {
@Override
public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser);
if (this.left instanceof ChangePathPatternParserVisitor.Target target) {
target.changeParser(parser);
}
if (this.right instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser);
if (this.right instanceof ChangePathPatternParserVisitor.Target target) {
target.changeParser(parser);
}
}
@ -837,8 +838,8 @@ public abstract class RequestPredicates {
@Override
public void changeParser(PathPatternParser parser) {
if (this.delegate instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) this.delegate).changeParser(parser);
if (this.delegate instanceof ChangePathPatternParserVisitor.Target target) {
target.changeParser(parser);
}
}
@ -904,11 +905,11 @@ public abstract class RequestPredicates {
@Override
public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) this.left).changeParser(parser);
if (this.left instanceof ChangePathPatternParserVisitor.Target target) {
target.changeParser(parser);
}
if (this.right instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) this.right).changeParser(parser);
if (this.right instanceof ChangePathPatternParserVisitor.Target target) {
target.changeParser(parser);
}
}
@ -923,7 +924,7 @@ public abstract class RequestPredicates {
private final ServerRequest request;
private RequestPath requestPath;
private final RequestPath requestPath;
private final Map<String, Object> attributes;

View File

@ -68,6 +68,7 @@ import org.springframework.web.util.pattern.PathPatternParser;
*
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 07.04.2003
* @see #getHandlerInternal
* @see #setDefaultHandler
@ -179,8 +180,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
@SuppressWarnings("deprecation")
public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setAlwaysUseFullPath(alwaysUseFullPath);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setAlwaysUseFullPath(alwaysUseFullPath);
}
}
@ -193,8 +194,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
@SuppressWarnings("deprecation")
public void setUrlDecode(boolean urlDecode) {
this.urlPathHelper.setUrlDecode(urlDecode);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setUrlDecode(urlDecode);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setUrlDecode(urlDecode);
}
}
@ -207,8 +208,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
@SuppressWarnings("deprecation")
public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setRemoveSemicolonContent(removeSemicolonContent);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setRemoveSemicolonContent(removeSemicolonContent);
}
}
@ -220,8 +221,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
this.urlPathHelper = urlPathHelper;
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setUrlPathHelper(urlPathHelper);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setUrlPathHelper(urlPathHelper);
}
}
@ -242,8 +243,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setPathMatcher(pathMatcher);
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setPathMatcher(pathMatcher);
}
}
@ -311,8 +312,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
public void setCorsConfigurationSource(CorsConfigurationSource source) {
Assert.notNull(source, "CorsConfigurationSource must not be null");
this.corsConfigurationSource = source;
if (source instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) source).setAllowInitLookupPath(false);
if (source instanceof UrlBasedCorsConfigurationSource urlConfigSource) {
urlConfigSource.setAllowInitLookupPath(false);
}
}
@ -437,11 +438,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
* @see WebRequestHandlerInterceptorAdapter
*/
protected HandlerInterceptor adaptInterceptor(Object interceptor) {
if (interceptor instanceof HandlerInterceptor) {
return (HandlerInterceptor) interceptor;
if (interceptor instanceof HandlerInterceptor handlerInterceptor) {
return handlerInterceptor;
}
else if (interceptor instanceof WebRequestInterceptor) {
return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor);
else if (interceptor instanceof WebRequestInterceptor webRequestInterceptor) {
return new WebRequestHandlerInterceptorAdapter(webRequestInterceptor);
}
else {
throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName());
@ -467,8 +468,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
protected final MappedInterceptor[] getMappedInterceptors() {
List<MappedInterceptor> mappedInterceptors = new ArrayList<>(this.adaptedInterceptors.size());
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
mappedInterceptors.add((MappedInterceptor) interceptor);
if (interceptor instanceof MappedInterceptor mappedInterceptor) {
mappedInterceptors.add(mappedInterceptor);
}
}
return (!mappedInterceptors.isEmpty() ? mappedInterceptors.toArray(new MappedInterceptor[0]) : null);
@ -502,8 +503,7 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
if (handler instanceof String handlerName) {
handler = obtainApplicationContext().getBean(handlerName);
}
@ -600,12 +600,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
* @see #getAdaptedInterceptors()
*/
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain handlerExecutionChain ?
handlerExecutionChain : new HandlerExecutionChain(handler));
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (interceptor instanceof MappedInterceptor mappedInterceptor) {
if (mappedInterceptor.matches(request)) {
chain.addInterceptor(mappedInterceptor.getInterceptor());
}
@ -622,8 +621,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
* @since 5.2
*/
protected boolean hasCorsConfigurationSource(Object handler) {
if (handler instanceof HandlerExecutionChain) {
handler = ((HandlerExecutionChain) handler).getHandler();
if (handler instanceof HandlerExecutionChain handlerExecutionChain) {
handler = handlerExecutionChain.getHandler();
}
return (handler instanceof CorsConfigurationSource || this.corsConfigurationSource != null);
}
@ -638,11 +637,11 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
@Nullable
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
Object resolvedHandler = handler;
if (handler instanceof HandlerExecutionChain) {
resolvedHandler = ((HandlerExecutionChain) handler).getHandler();
if (handler instanceof HandlerExecutionChain handlerExecutionChain) {
resolvedHandler = handlerExecutionChain.getHandler();
}
if (resolvedHandler instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) resolvedHandler).getCorsConfiguration(request);
if (resolvedHandler instanceof CorsConfigurationSource configSource) {
return configSource.getCorsConfiguration(request);
}
return null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -43,8 +43,7 @@ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHan
if (handler == null) {
return super.shouldApplyTo(request, null);
}
else if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
else if (handler instanceof HandlerMethod handlerMethod) {
handler = handlerMethod.getBean();
return super.shouldApplyTo(request, handler);
}

View File

@ -273,8 +273,8 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
* @see #getMappingForMethod
*/
protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
Class<?> handlerType = (handler instanceof String beanName ?
obtainApplicationContext().getType(beanName) : handler.getClass());
if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
@ -339,8 +339,8 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
* @return the created HandlerMethod
*/
protected HandlerMethod createHandlerMethod(Object handler, Method method) {
if (handler instanceof String) {
return new HandlerMethod((String) handler,
if (handler instanceof String beanName) {
return new HandlerMethod(beanName,
obtainApplicationContext().getAutowireCapableBeanFactory(),
obtainApplicationContext(),
method);
@ -479,15 +479,14 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
@Override
protected boolean hasCorsConfigurationSource(Object handler) {
return super.hasCorsConfigurationSource(handler) ||
(handler instanceof HandlerMethod &&
this.mappingRegistry.getCorsConfiguration((HandlerMethod) handler) != null);
(handler instanceof HandlerMethod handerMethod &&
this.mappingRegistry.getCorsConfiguration(handerMethod) != null);
}
@Override
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
CorsConfiguration corsConfig = super.getCorsConfiguration(handler, request);
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handler instanceof HandlerMethod handlerMethod) {
if (handlerMethod.equals(PREFLIGHT_AMBIGUOUS_MATCH)) {
return AbstractHandlerMethodMapping.ALLOW_CORS_CONFIG;
}

View File

@ -163,8 +163,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
}
if (rawHandler != null) {
// Bean name or resolved handler?
if (rawHandler instanceof String) {
String handlerName = (String) rawHandler;
if (rawHandler instanceof String handlerName) {
rawHandler = obtainApplicationContext().getBean(handlerName);
}
validateHandler(rawHandler, request);
@ -211,8 +210,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
}
PathPattern pattern = matches.get(0);
handler = this.pathPatternHandlerMap.get(pattern);
if (handler instanceof String) {
String handlerName = (String) handler;
if (handler instanceof String handlerName) {
handler = obtainApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
@ -270,8 +268,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
}
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
if (handler instanceof String handlerName) {
handler = obtainApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
@ -302,8 +299,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
Object handler = this.handlerMap.get(urlPath);
if (handler != null) {
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
if (handler instanceof String handlerName) {
handler = obtainApplicationContext().getBean(handlerName);
}
validateHandler(handler, request);
@ -413,8 +409,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
Object resolvedHandler = handler;
// Eagerly resolve handler if referencing singleton via name.
if (!this.lazyInitHandlers && handler instanceof String) {
String handlerName = (String) handler;
if (!this.lazyInitHandlers && handler instanceof String handlerName) {
ApplicationContext applicationContext = obtainApplicationContext();
if (applicationContext.isSingleton(handlerName)) {
resolvedHandler = applicationContext.getBean(handlerName);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ public class SimpleMappingExceptionResolver extends AbstractHandlerExceptionReso
@Nullable
private Integer defaultStatusCode;
private Map<String, Integer> statusCodes = new HashMap<>();
private final Map<String, Integer> statusCodes = new HashMap<>();
@Nullable
private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -75,8 +75,7 @@ public class WebRequestHandlerInterceptorAdapter implements AsyncHandlerIntercep
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (this.requestInterceptor instanceof AsyncWebRequestInterceptor) {
AsyncWebRequestInterceptor asyncInterceptor = (AsyncWebRequestInterceptor) this.requestInterceptor;
if (this.requestInterceptor instanceof AsyncWebRequestInterceptor asyncInterceptor) {
DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request, response);
asyncInterceptor.afterConcurrentHandlingStarted(webRequest);
}

View File

@ -67,8 +67,7 @@ public class ParameterizableViewController extends AbstractController {
*/
@Nullable
public String getViewName() {
if (this.view instanceof String) {
String viewName = (String) this.view;
if (this.view instanceof String viewName) {
if (getStatusCode() != null && getStatusCode().is3xxRedirection()) {
return viewName.startsWith("redirect:") ? viewName : "redirect:" + viewName;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -80,9 +80,9 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
private PathMatcher pathMatcher = defaultPathMatcher;
private Map<PathPattern, Integer> cacheMappings = new HashMap<>();
private final Map<PathPattern, Integer> cacheMappings = new HashMap<>();
private Map<PathPattern, CacheControl> cacheControlMappings = new HashMap<>();
private final Map<PathPattern, CacheControl> cacheControlMappings = new HashMap<>();
/**
@ -215,8 +215,8 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
}
if (!ObjectUtils.isEmpty(this.cacheControlMappings)) {
CacheControl control = (path instanceof PathContainer ?
lookupCacheControl((PathContainer) path) : lookupCacheControl((String) path));
CacheControl control = (path instanceof PathContainer pathContainer ?
lookupCacheControl(pathContainer) : lookupCacheControl((String) path));
if (control != null) {
if (logger.isTraceEnabled()) {
logger.trace("Applying " + control);
@ -227,8 +227,8 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
}
if (!ObjectUtils.isEmpty(this.cacheMappings)) {
Integer cacheSeconds = (path instanceof PathContainer ?
lookupCacheSeconds((PathContainer) path) : lookupCacheSeconds((String) path));
Integer cacheSeconds = (path instanceof PathContainer pathContainer ?
lookupCacheSeconds(pathContainer) : lookupCacheSeconds((String) path));
if (cacheSeconds != null) {
if (logger.isTraceEnabled()) {
logger.trace("Applying cacheSeconds " + cacheSeconds);

View File

@ -470,10 +470,9 @@ public final class RequestMappingInfo implements RequestCondition<RequestMapping
if (this == other) {
return true;
}
if (!(other instanceof RequestMappingInfo)) {
if (!(other instanceof RequestMappingInfo otherInfo)) {
return false;
}
RequestMappingInfo otherInfo = (RequestMappingInfo) other;
return (getActivePatternsCondition().equals(otherInfo.getActivePatternsCondition()) &&
this.methodsCondition.equals(otherInfo.methodsCondition) &&
this.paramsCondition.equals(otherInfo.paramsCondition) &&

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -63,6 +63,7 @@ import org.springframework.web.servlet.support.RequestContextUtils;
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @author Brian Clozel
* @author Sam Brannen
* @since 3.1
*/
public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodProcessor {
@ -149,8 +150,7 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
private Type getHttpEntityType(MethodParameter parameter) {
Assert.isAssignable(HttpEntity.class, parameter.getParameterType());
Type parameterType = parameter.getGenericParameterType();
if (parameterType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) parameterType;
if (parameterType instanceof ParameterizedType type) {
if (type.getActualTypeArguments().length != 1) {
throw new IllegalArgumentException("Expected single generic parameter on '" +
parameter.getParameterName() + "' in method " + parameter.getMethod());
@ -178,10 +178,10 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);
Assert.isInstanceOf(HttpEntity.class, returnValue);
HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;
HttpEntity<?> httpEntity = (HttpEntity<?>) returnValue;
HttpHeaders outputHeaders = outputMessage.getHeaders();
HttpHeaders entityHeaders = responseEntity.getHeaders();
HttpHeaders entityHeaders = httpEntity.getHeaders();
if (!entityHeaders.isEmpty()) {
entityHeaders.forEach((key, value) -> {
if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
@ -196,8 +196,8 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
});
}
if (responseEntity instanceof ResponseEntity) {
int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
if (httpEntity instanceof ResponseEntity<?> responseEntity) {
int returnStatus = responseEntity.getStatusCodeValue();
outputMessage.getServletResponse().setStatus(returnStatus);
if (returnStatus == 200) {
HttpMethod method = inputMessage.getMethod();
@ -216,7 +216,7 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
}
// Try even with null body. ResponseBodyAdvice could get involved.
writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);
writeWithMessageConverters(httpEntity.getBody(), returnType, inputMessage, outputMessage);
// Ensure headers are flushed even if no body was written.
outputMessage.flush();
@ -261,8 +261,8 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro
private void saveFlashAttributes(ModelAndViewContainer mav, NativeWebRequest request, String location) {
mav.setRedirectModelScenario(true);
ModelMap model = mav.getModel();
if (model instanceof RedirectAttributes) {
Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
if (model instanceof RedirectAttributes redirectAttributes) {
Map<String, ?> flashAttributes = redirectAttributes.getFlashAttributes();
if (!CollectionUtils.isEmpty(flashAttributes)) {
HttpServletRequest req = request.getNativeRequest(HttpServletRequest.class);
HttpServletResponse res = request.getNativeResponse(HttpServletResponse.class);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,8 +61,8 @@ class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyA
if (requestResponseBodyAdvice != null) {
List<T> result = new ArrayList<>();
for (Object advice : requestResponseBodyAdvice) {
Class<?> beanType = (advice instanceof ControllerAdviceBean ?
((ControllerAdviceBean) advice).getBeanType() : advice.getClass());
Class<?> beanType = (advice instanceof ControllerAdviceBean adviceBean ?
adviceBean.getBeanType() : advice.getClass());
if (beanType != null && adviceType.isAssignableFrom(beanType)) {
result.add((T) advice);
}
@ -153,8 +153,7 @@ class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyA
}
List<A> result = new ArrayList<>(availableAdvice.size());
for (Object advice : availableAdvice) {
if (advice instanceof ControllerAdviceBean) {
ControllerAdviceBean adviceBean = (ControllerAdviceBean) advice;
if (advice instanceof ControllerAdviceBean adviceBean) {
if (!adviceBean.isApplicableToBeanType(parameter.getContainingClass())) {
continue;
}

View File

@ -230,8 +230,7 @@ public abstract class ResponseEntityExceptionHandler {
List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
if (!CollectionUtils.isEmpty(mediaTypes)) {
headers.setAccept(mediaTypes);
if (request instanceof ServletWebRequest) {
ServletWebRequest servletWebRequest = (ServletWebRequest) request;
if (request instanceof ServletWebRequest servletWebRequest) {
if (HttpMethod.PATCH.equals(servletWebRequest.getHttpMethod())) {
headers.setAcceptPatch(mediaTypes);
}
@ -437,8 +436,7 @@ public abstract class ResponseEntityExceptionHandler {
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {
if (webRequest instanceof ServletWebRequest) {
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
if (webRequest instanceof ServletWebRequest servletWebRequest) {
HttpServletResponse response = servletWebRequest.getResponse();
if (response != null && response.isCommitted()) {
if (logger.isWarnEnabled()) {

View File

@ -50,8 +50,7 @@ public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHan
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue instanceof View) {
View view = (View) returnValue;
if (returnValue instanceof View view) {
mavContainer.setView(view);
if (view instanceof SmartView && ((SmartView) view).isRedirectView()) {
mavContainer.setRedirectModelScenario(true);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -235,10 +235,9 @@ public class CssLinkResourceTransformer extends ResourceTransformerSupport {
if (this == other) {
return true;
}
if (!(other instanceof ContentChunkInfo)) {
if (!(other instanceof ContentChunkInfo otherCci)) {
return false;
}
ContentChunkInfo otherCci = (ContentChunkInfo) other;
return (this.start == otherCci.start && this.end == otherCci.end);
}

View File

@ -237,12 +237,12 @@ public class PathResourceResolver extends AbstractResourceResolver {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(location.getURL().toString());
}
else if (resource instanceof ClassPathResource) {
resourcePath = ((ClassPathResource) resource).getPath();
else if (resource instanceof ClassPathResource classPathResource) {
resourcePath = classPathResource.getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath());
}
else if (resource instanceof ServletContextResource) {
resourcePath = ((ServletContextResource) resource).getPath();
else if (resource instanceof ServletContextResource servletContextResource) {
resourcePath = servletContextResource.getPath();
locationPath = StringUtils.cleanPath(((ServletContextResource) location).getPath());
}
else {
@ -301,11 +301,8 @@ public class PathResourceResolver extends AbstractResourceResolver {
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// Should never happen...
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// May not be possible to decode... | Should never happen...
}
}
return false;

View File

@ -484,8 +484,7 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
return;
}
for (int i = getResourceResolvers().size() - 1; i >= 0; i--) {
if (getResourceResolvers().get(i) instanceof PathResourceResolver) {
PathResourceResolver pathResolver = (PathResourceResolver) getResourceResolvers().get(i);
if (getResourceResolvers().get(i) instanceof PathResourceResolver pathResolver) {
if (ObjectUtils.isEmpty(pathResolver.getAllowedLocations())) {
pathResolver.setAllowedLocations(getLocations().toArray(new Resource[0]));
}
@ -681,11 +680,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
return true;
}
}
catch (IllegalArgumentException ex) {
// May not be possible to decode...
}
catch (UnsupportedEncodingException ex) {
// Should never happen...
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// May not be possible to decode... | Should never happen...
}
}
return false;
@ -788,8 +784,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
response.setContentType(mediaType.toString());
}
if (resource instanceof HttpResource) {
HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
if (resource instanceof HttpResource httpResource) {
HttpHeaders resourceHeaders = httpResource.getResponseHeaders();
resourceHeaders.forEach((headerName, headerValues) -> {
boolean first = true;
for (String headerValue : headerValues) {

View File

@ -154,8 +154,7 @@ public class ResourceUrlProvider implements ApplicationListener<ContextRefreshed
for (SimpleUrlHandlerMapping mapping : mappings) {
for (String pattern : mapping.getHandlerMap().keySet()) {
Object handler = mapping.getHandlerMap().get(pattern);
if (handler instanceof ResourceHttpRequestHandler) {
ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler;
if (handler instanceof ResourceHttpRequestHandler resourceHandler) {
this.handlerMap.put(pattern, resourceHandler);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -65,7 +65,7 @@ import org.springframework.util.StringUtils;
*/
public class VersionResourceResolver extends AbstractResourceResolver {
private AntPathMatcher pathMatcher = new AntPathMatcher();
private final AntPathMatcher pathMatcher = new AntPathMatcher();
/** Map from path pattern -> VersionStrategy. */
private final Map<String, VersionStrategy> versionStrategyMap = new LinkedHashMap<>();
@ -311,8 +311,8 @@ public class VersionResourceResolver extends AbstractResourceResolver {
@Override
public HttpHeaders getResponseHeaders() {
HttpHeaders headers = (this.original instanceof HttpResource ?
((HttpResource) this.original).getResponseHeaders() : new HttpHeaders());
HttpHeaders headers = (this.original instanceof HttpResource httpResource ?
httpResource.getResponseHeaders() : new HttpHeaders());
headers.setETag("W/\"" + this.version + "\"");
return headers;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,7 +40,7 @@ import org.springframework.lang.Nullable;
*/
public class JspAwareRequestContext extends RequestContext {
private PageContext pageContext;
private final PageContext pageContext;
/**
@ -115,13 +115,13 @@ public class JspAwareRequestContext extends RequestContext {
@Nullable
public static Locale getJstlLocale(PageContext pageContext) {
Object localeObject = Config.find(pageContext, Config.FMT_LOCALE);
return (localeObject instanceof Locale ? (Locale) localeObject : null);
return (localeObject instanceof Locale locale ? locale : null);
}
@Nullable
public static TimeZone getJstlTimeZone(PageContext pageContext) {
Object timeZoneObject = Config.find(pageContext, Config.FMT_TIME_ZONE);
return (timeZoneObject instanceof TimeZone ? (TimeZone) timeZoneObject : null);
return (timeZoneObject instanceof TimeZone timeZone ? timeZone : null);
}
}

View File

@ -95,15 +95,15 @@ public class RequestContext {
protected static final boolean jstlPresent = ClassUtils.isPresent(
"jakarta.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader());
private HttpServletRequest request;
private final HttpServletRequest request;
@Nullable
private HttpServletResponse response;
private final HttpServletResponse response;
@Nullable
private Map<String, Object> model;
private final Map<String, Object> model;
private WebApplicationContext webApplicationContext;
private final WebApplicationContext webApplicationContext;
@Nullable
private Locale locale;
@ -118,7 +118,7 @@ public class RequestContext {
private Boolean defaultHtmlEscape;
@Nullable
private Boolean responseEncodedHtmlEscape;
private final Boolean responseEncodedHtmlEscape;
private UrlPathHelper urlPathHelper;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -35,7 +35,7 @@ import org.springframework.web.servlet.support.BindStatus;
*
* <p><h1><a name="equality-contract">Equality Contract</a></h1>
* For single-valued objects equality is first tested using standard {@link Object#equals Java equality}. As
* such, user code should endeavour to implement {@link Object#equals} to speed up the comparison process. If
* such, user code should endeavor to implement {@link Object#equals} to speed up the comparison process. If
* {@link Object#equals} returns {@code false} then an attempt is made at an
* {@link #exhaustiveCompare exhaustive comparison} with the aim being to <strong>prove</strong> equality rather
* than disprove it.
@ -86,11 +86,11 @@ abstract class SelectedValueComparator {
if (boundValue.getClass().isArray()) {
selected = collectionCompare(CollectionUtils.arrayToList(boundValue), candidateValue, bindStatus);
}
else if (boundValue instanceof Collection) {
selected = collectionCompare((Collection<?>) boundValue, candidateValue, bindStatus);
else if (boundValue instanceof Collection<?> collection) {
selected = collectionCompare(collection, candidateValue, bindStatus);
}
else if (boundValue instanceof Map) {
selected = mapCompare((Map<?, ?>) boundValue, candidateValue, bindStatus);
else if (boundValue instanceof Map<?, ?> map) {
selected = mapCompare(map, candidateValue, bindStatus);
}
}
if (!selected) {
@ -163,9 +163,8 @@ abstract class SelectedValueComparator {
return true;
}
if (editor != null && candidate instanceof String) {
if (editor != null && candidate instanceof String candidateAsString) {
// Try PE-based comparison (PE should *not* be allowed to escape creating thread)
String candidateAsString = (String) candidate;
Object candidateAsValue;
if (convertedValueCache != null && convertedValueCache.containsKey(editor)) {
candidateAsValue = convertedValueCache.get(editor);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -79,7 +79,7 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu
/** Map from view key to View instance, synchronized for View creation. */
@SuppressWarnings("serial")
private final Map<Object, View> viewCreationCache =
new LinkedHashMap<Object, View>(DEFAULT_CACHE_LIMIT, 0.75f, true) {
new LinkedHashMap<>(DEFAULT_CACHE_LIMIT, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Object, View> eldest) {
if (size() > getCacheLimit()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -332,8 +332,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport
@Nullable
private View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes, RequestAttributes attrs) {
for (View candidateView : candidateViews) {
if (candidateView instanceof SmartView) {
SmartView smartView = (SmartView) candidateView;
if (candidateView instanceof SmartView smartView) {
if (smartView.isRedirectView()) {
return candidateView;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -212,8 +212,7 @@ public abstract class AbstractJackson2View extends AbstractView {
Class<?> serializationView = null;
FilterProvider filters = null;
if (value instanceof MappingJacksonValue) {
MappingJacksonValue container = (MappingJacksonValue) value;
if (value instanceof MappingJacksonValue container) {
value = container.getValue();
serializationView = container.getSerializationView();
filters = container.getFilters();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -470,10 +470,9 @@ public class ScriptTemplateView extends AbstractUrlBasedView {
if (this == other) {
return true;
}
if (!(other instanceof EngineKey)) {
if (!(other instanceof EngineKey otherKey)) {
return false;
}
EngineKey otherKey = (EngineKey) other;
return (this.engineName.equals(otherKey.engineName) && Arrays.equals(this.scripts, otherKey.scripts));
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -302,32 +302,31 @@ public class XsltView extends AbstractUrlBasedView {
/**
* Convert the supplied {@link Object} into an XSLT {@link Source} if the
* {@link Object} type is {@link #getSourceTypes() supported}.
* @param source the original source object
* @param sourceObject the original source object
* @return the adapted XSLT Source
* @throws IllegalArgumentException if the given Object is not of a supported type
*/
protected Source convertSource(Object source) throws Exception {
if (source instanceof Source) {
return (Source) source;
protected Source convertSource(Object sourceObject) throws Exception {
if (sourceObject instanceof Source source) {
return source;
}
else if (source instanceof Document) {
return new DOMSource(((Document) source).getDocumentElement());
else if (sourceObject instanceof Document document) {
return new DOMSource(document.getDocumentElement());
}
else if (source instanceof Node) {
return new DOMSource((Node) source);
else if (sourceObject instanceof Node node) {
return new DOMSource(node);
}
else if (source instanceof Reader) {
return new StreamSource((Reader) source);
else if (sourceObject instanceof Reader reader) {
return new StreamSource(reader);
}
else if (source instanceof InputStream) {
return new StreamSource((InputStream) source);
else if (sourceObject instanceof InputStream inputStream) {
return new StreamSource(inputStream);
}
else if (source instanceof Resource) {
Resource resource = (Resource) source;
else if (sourceObject instanceof Resource resource) {
return new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString());
}
else {
throw new IllegalArgumentException("Value '" + source + "' cannot be converted to XSLT Source");
throw new IllegalArgumentException("Value '" + sourceObject + "' cannot be converted to XSLT Source");
}
}
@ -481,8 +480,7 @@ public class XsltView extends AbstractUrlBasedView {
* @param source the XSLT Source to close (may be {@code null})
*/
private void closeSourceIfNecessary(@Nullable Source source) {
if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
if (source instanceof StreamSource streamSource) {
if (streamSource.getReader() != null) {
try {
streamSource.getReader().close();