Use pattern matching for instanceof where appropriate

See gh-31475
pull/31477/head
dreis2211 2 years ago committed by Andy Wilkinson
parent a7b98e7312
commit 5db04da275

@ -120,10 +120,10 @@ class AsciidoctorConventions {
configureOptions(asciidoctorTask);
asciidoctorTask.baseDirFollowsSourceDir();
createSyncDocumentationSourceTask(project, asciidoctorTask);
if (asciidoctorTask instanceof AsciidoctorTask) {
boolean pdf = asciidoctorTask.getName().toLowerCase().contains("pdf");
if (asciidoctorTask instanceof AsciidoctorTask task) {
boolean pdf = task.getName().toLowerCase().contains("pdf");
String backend = (!pdf) ? "spring-html" : "spring-pdf";
((AsciidoctorTask) asciidoctorTask).outputOptions((outputOptions) -> outputOptions.backends(backend));
task.outputOptions((outputOptions) -> outputOptions.backends(backend));
}
}

@ -300,7 +300,7 @@ public class BomExtension {
public void setModules(List<Object> modules) {
this.modules = modules.stream()
.map((input) -> (input instanceof Module) ? (Module) input : new Module((String) input))
.map((input) -> (input instanceof Module module) ? module : new Module((String) input))
.collect(Collectors.toList());
}
@ -315,9 +315,8 @@ public class BomExtension {
public Object methodMissing(String name, Object args) {
if (args instanceof Object[] && ((Object[]) args).length == 1) {
Object arg = ((Object[]) args)[0];
if (arg instanceof Closure) {
if (arg instanceof Closure closure) {
ModuleHandler moduleHandler = new ModuleHandler();
Closure<?> closure = (Closure<?>) arg;
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.setDelegate(moduleHandler);
closure.call(moduleHandler);

@ -255,9 +255,8 @@ public class BomPlugin implements Plugin<Project> {
private Node findChild(Node parent, String name) {
for (Object child : parent.children()) {
if (child instanceof Node) {
Node node = (Node) child;
if ((node.name() instanceof QName) && name.equals(((QName) node.name()).getLocalPart())) {
if (child instanceof Node node) {
if ((node.name() instanceof QName qname) && name.equals(qname.getLocalPart())) {
return node;
}
if (name.equals(node.name())) {
@ -276,9 +275,8 @@ public class BomPlugin implements Plugin<Project> {
}
private boolean isNodeWithName(Object candidate, String name) {
if (candidate instanceof Node) {
Node node = (Node) candidate;
if ((node.name() instanceof QName) && name.equals(((QName) node.name()).getLocalPart())) {
if (candidate instanceof Node node) {
if ((node.name() instanceof QName qname) && name.equals(qname.getLocalPart())) {
return true;
}
if (name.equals(node.name())) {

@ -63,8 +63,8 @@ final class StandardGitHubRepository implements GitHubRepository {
return (Integer) response.getBody().get("number");
}
catch (RestClientException ex) {
if (ex instanceof Forbidden) {
System.out.println("Received 403 response with headers " + ((Forbidden) ex).getResponseHeaders());
if (ex instanceof Forbidden forbidden) {
System.out.println("Received 403 response with headers " + forbidden.getResponseHeaders());
}
throw ex;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -33,8 +33,8 @@ abstract class AbstractDependencyVersion implements DependencyVersion {
@Override
public int compareTo(DependencyVersion other) {
ComparableVersion otherComparable = (other instanceof AbstractDependencyVersion)
? ((AbstractDependencyVersion) other).comparableVersion : new ComparableVersion(other.toString());
ComparableVersion otherComparable = (other instanceof AbstractDependencyVersion otherVersion)
? otherVersion.comparableVersion : new ComparableVersion(other.toString());
return this.comparableVersion.compareTo(otherComparable);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -83,8 +83,8 @@ class ArtifactVersionDependencyVersion extends AbstractDependencyVersion {
protected Optional<ArtifactVersionDependencyVersion> extractArtifactVersionDependencyVersion(
DependencyVersion other) {
ArtifactVersionDependencyVersion artifactVersion = null;
if (other instanceof ArtifactVersionDependencyVersion) {
artifactVersion = (ArtifactVersionDependencyVersion) other;
if (other instanceof ArtifactVersionDependencyVersion otherVersion) {
artifactVersion = otherVersion;
}
return Optional.ofNullable(artifactVersion);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -47,10 +47,9 @@ final class ReleaseTrainDependencyVersion implements DependencyVersion {
@Override
public int compareTo(DependencyVersion other) {
if (!(other instanceof ReleaseTrainDependencyVersion)) {
if (!(other instanceof ReleaseTrainDependencyVersion otherReleaseTrain)) {
return -1;
}
ReleaseTrainDependencyVersion otherReleaseTrain = (ReleaseTrainDependencyVersion) other;
int comparison = this.releaseTrain.compareTo(otherReleaseTrain.releaseTrain);
if (comparison != 0) {
return comparison;
@ -67,10 +66,9 @@ final class ReleaseTrainDependencyVersion implements DependencyVersion {
if (other instanceof CalendarVersionDependencyVersion) {
return false;
}
if (!(other instanceof ReleaseTrainDependencyVersion)) {
if (!(other instanceof ReleaseTrainDependencyVersion otherReleaseTrain)) {
return true;
}
ReleaseTrainDependencyVersion otherReleaseTrain = (ReleaseTrainDependencyVersion) other;
return otherReleaseTrain.compareTo(this) < 0;
}
@ -84,10 +82,9 @@ final class ReleaseTrainDependencyVersion implements DependencyVersion {
if (other instanceof CalendarVersionDependencyVersion) {
return false;
}
if (!(other instanceof ReleaseTrainDependencyVersion)) {
if (!(other instanceof ReleaseTrainDependencyVersion otherReleaseTrain)) {
return true;
}
ReleaseTrainDependencyVersion otherReleaseTrain = (ReleaseTrainDependencyVersion) other;
return otherReleaseTrain.releaseTrain.equals(this.releaseTrain) && isNewerThan(other);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,8 +79,8 @@ public class CheckClasspathForUnnecessaryExclusions extends DefaultTask {
}
private void processDependency(Dependency dependency) {
if (dependency instanceof ModuleDependency) {
processDependency((ModuleDependency) dependency);
if (dependency instanceof ModuleDependency moduleDependency) {
processDependency(moduleDependency);
}
}

@ -373,9 +373,7 @@ public class MavenPluginPlugin implements Plugin<Project> {
@TaskAction
public void createRepository() {
for (ResolvedArtifactResult result : this.runtimeClasspath.getIncoming().getArtifacts()) {
if (result.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier) {
ModuleComponentIdentifier identifier = (ModuleComponentIdentifier) result.getId()
.getComponentIdentifier();
if (result.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier identifier) {
String fileName = result.getFile().getName()
.replace(identifier.getVersion() + "-" + identifier.getVersion(), identifier.getVersion());
File repositoryLocation = this.outputDirectory.dir(identifier.getGroup().replace('.', '/') + "/"

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -93,8 +93,7 @@ class CloudFoundrySecurityInterceptor {
}
private Mono<SecurityResponse> getErrorResponse(Throwable throwable) {
if (throwable instanceof CloudFoundryAuthorizationException) {
CloudFoundryAuthorizationException cfException = (CloudFoundryAuthorizationException) throwable;
if (throwable instanceof CloudFoundryAuthorizationException cfException) {
return Mono.just(new SecurityResponse(cfException.getStatusCode(),
"{\"security_error\":\"" + cfException.getMessage() + "\"}"));
}

@ -164,8 +164,8 @@ public class ReactiveCloudFoundryActuatorAutoConfiguration {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebFilterChainProxy) {
return postProcess((WebFilterChainProxy) bean);
if (bean instanceof WebFilterChainProxy webFilterChainProxy) {
return postProcess(webFilterChainProxy);
}
return bean;
}

@ -90,8 +90,8 @@ class ReactiveCloudFoundrySecurityService {
}
private Throwable mapError(Throwable throwable) {
if (throwable instanceof WebClientResponseException) {
HttpStatusCode statusCode = ((WebClientResponseException) throwable).getStatusCode();
if (throwable instanceof WebClientResponseException webClientResponseException) {
HttpStatusCode statusCode = webClientResponseException.getStatusCode();
if (statusCode.equals(HttpStatus.FORBIDDEN)) {
return new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
}

@ -77,8 +77,7 @@ class CloudFoundrySecurityInterceptor {
}
catch (Exception ex) {
logger.error(ex);
if (ex instanceof CloudFoundryAuthorizationException) {
CloudFoundryAuthorizationException cfException = (CloudFoundryAuthorizationException) ex;
if (ex instanceof CloudFoundryAuthorizationException cfException) {
return new SecurityResponse(cfException.getStatusCode(),
"{\"security_error\":\"" + cfException.getMessage() + "\"}");
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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,8 +40,8 @@ class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFacto
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
prepareHttpsConnection((HttpsURLConnection) connection);
if (connection instanceof HttpsURLConnection httpsURLConnection) {
prepareHttpsConnection(httpsURLConnection);
}
super.prepareConnection(connection, httpMethod);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -72,8 +72,8 @@ public class ConditionsReportEndpoint {
private ConfigurableApplicationContext getConfigurableParent(ConfigurableApplicationContext context) {
ApplicationContext parent = context.getParent();
if (parent instanceof ConfigurableApplicationContext) {
return (ConfigurableApplicationContext) parent;
if (parent instanceof ConfigurableApplicationContext configurableParent) {
return configurableParent;
}
return null;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,8 +65,8 @@ class AutoConfiguredHealthEndpointGroups implements HealthEndpointGroups {
* @param properties the health endpoint properties
*/
AutoConfiguredHealthEndpointGroups(ApplicationContext applicationContext, HealthEndpointProperties properties) {
ListableBeanFactory beanFactory = (applicationContext instanceof ConfigurableApplicationContext)
? ((ConfigurableApplicationContext) applicationContext).getBeanFactory() : applicationContext;
ListableBeanFactory beanFactory = (applicationContext instanceof ConfigurableApplicationContext configurableContext)
? configurableContext.getBeanFactory() : applicationContext;
Show showComponents = properties.getShowComponents();
Show showDetails = properties.getShowDetails();
Set<String> roles = properties.getRoles();

@ -113,8 +113,8 @@ class HealthEndpointConfiguration {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof HealthEndpointGroups) {
return applyPostProcessors((HealthEndpointGroups) bean);
if (bean instanceof HealthEndpointGroups groups) {
return applyPostProcessors(groups);
}
return bean;
}
@ -145,11 +145,11 @@ class HealthEndpointConfiguration {
}
private HealthContributor adapt(ReactiveHealthContributor contributor) {
if (contributor instanceof ReactiveHealthIndicator) {
return adapt((ReactiveHealthIndicator) contributor);
if (contributor instanceof ReactiveHealthIndicator healthIndicator) {
return adapt(healthIndicator);
}
if (contributor instanceof CompositeReactiveHealthContributor) {
return adapt((CompositeReactiveHealthContributor) contributor);
if (contributor instanceof CompositeReactiveHealthContributor healthContributor) {
return adapt(healthContributor);
}
throw new IllegalStateException("Unsupported ReactiveHealthContributor type " + contributor.getClass());
}

@ -103,8 +103,7 @@ public class DataSourceHealthContributorAutoConfiguration implements Initializin
}
private HealthContributor createContributor(DataSource source) {
if (source instanceof AbstractRoutingDataSource) {
AbstractRoutingDataSource routingDataSource = (AbstractRoutingDataSource) source;
if (source instanceof AbstractRoutingDataSource routingDataSource) {
return new RoutingDataSourceHealthContributor(routingDataSource, this::createContributor);
}
return new DataSourceHealthIndicator(source, getValidationQuery(source));

@ -57,8 +57,8 @@ public class LiquibaseEndpointAutoConfiguration {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DataSourceClosingSpringLiquibase) {
((DataSourceClosingSpringLiquibase) bean).setCloseDataSourceOnceMigrated(false);
if (bean instanceof DataSourceClosingSpringLiquibase dataSource) {
dataSource.setCloseDataSourceOnceMigrated(false);
}
return bean;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -60,8 +60,8 @@ class MeterRegistryPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MeterRegistry) {
getConfigurer().configure((MeterRegistry) bean);
if (bean instanceof MeterRegistry meterRegistry) {
getConfigurer().configure(meterRegistry);
}
return bean;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,18 +63,18 @@ public final class MeterValue {
}
private Double getDistributionSummaryValue() {
if (this.value instanceof Double) {
return (Double) this.value;
if (this.value instanceof Double doubleValue) {
return doubleValue;
}
return null;
}
private Long getTimerValue() {
if (this.value instanceof Double) {
return TimeUnit.MILLISECONDS.toNanos(((Double) this.value).longValue());
if (this.value instanceof Double doubleValue) {
return TimeUnit.MILLISECONDS.toNanos(doubleValue.longValue());
}
if (this.value instanceof Duration) {
return ((Duration) this.value).toNanos();
if (this.value instanceof Duration duration) {
return duration.toNanos();
}
return null;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -49,8 +49,8 @@ class RabbitConnectionFactoryMetricsPostProcessor implements BeanPostProcessor,
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof AbstractConnectionFactory) {
bindConnectionFactoryToRegistry(getMeterRegistry(), beanName, (AbstractConnectionFactory) bean);
if (bean instanceof AbstractConnectionFactory connectionFactory) {
bindConnectionFactoryToRegistry(getMeterRegistry(), beanName, connectionFactory);
}
return bean;
}

@ -60,8 +60,8 @@ public class ConnectionPoolMetricsAutoConfiguration {
}
private ConnectionPool extractPool(Object candidate) {
if (candidate instanceof ConnectionPool) {
return (ConnectionPool) candidate;
if (candidate instanceof ConnectionPool connectionPool) {
return connectionPool;
}
if (candidate instanceof Wrapped) {
return extractPool(((Wrapped<?>) candidate).unwrap());

@ -54,11 +54,11 @@ public class TaskExecutorMetricsAutoConfiguration {
@Autowired
public void bindTaskExecutorsToRegistry(Map<String, Executor> executors, MeterRegistry registry) {
executors.forEach((beanName, executor) -> {
if (executor instanceof ThreadPoolTaskExecutor) {
monitor(registry, safeGetThreadPoolExecutor((ThreadPoolTaskExecutor) executor), beanName);
if (executor instanceof ThreadPoolTaskExecutor threadPoolTaskExecutor) {
monitor(registry, safeGetThreadPoolExecutor(threadPoolTaskExecutor), beanName);
}
else if (executor instanceof ThreadPoolTaskScheduler) {
monitor(registry, safeGetThreadPoolExecutor((ThreadPoolTaskScheduler) executor), beanName);
else if (executor instanceof ThreadPoolTaskScheduler threadPoolTaskScheduler) {
monitor(registry, safeGetThreadPoolExecutor(threadPoolTaskScheduler), beanName);
}
});
}

@ -60,8 +60,8 @@ class ObservationRegistryPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof ObservationRegistry) {
getConfigurer().configure((ObservationRegistry) bean);
if (bean instanceof ObservationRegistry registry) {
getConfigurer().configure(registry);
}
return bean;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -227,11 +227,11 @@ public final class EndpointRequest {
}
private EndpointId getEndpointId(Object source) {
if (source instanceof EndpointId) {
return (EndpointId) source;
if (source instanceof EndpointId endpointId) {
return endpointId;
}
if (source instanceof String) {
return (EndpointId.of((String) source));
if (source instanceof String string) {
return EndpointId.of(string);
}
if (source instanceof Class) {
return getEndpointId((Class<?>) source);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -249,11 +249,11 @@ public final class EndpointRequest {
}
private EndpointId getEndpointId(Object source) {
if (source instanceof EndpointId) {
return (EndpointId) source;
if (source instanceof EndpointId endpointId) {
return endpointId;
}
if (source instanceof String) {
return (EndpointId.of((String) source));
if (source instanceof String string) {
return EndpointId.of(string);
}
if (source instanceof Class) {
return getEndpointId((Class<?>) source);

@ -205,11 +205,11 @@ class ChildManagementContextInitializer implements ApplicationListener<WebServer
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
if (event instanceof ContextClosedEvent contextClosedEvent) {
onContextClosedEvent(contextClosedEvent);
}
if (event instanceof ApplicationFailedEvent) {
onApplicationFailedEvent((ApplicationFailedEvent) event);
if (event instanceof ApplicationFailedEvent applicationFailedEvent) {
onApplicationFailedEvent(applicationFailedEvent);
}
}

@ -62,8 +62,8 @@ public class ManagementContextAutoConfiguration {
public void afterSingletonsInstantiated() {
verifySslConfiguration();
verifyAddressConfiguration();
if (this.environment instanceof ConfigurableEnvironment) {
addLocalManagementPortPropertyAlias((ConfigurableEnvironment) this.environment);
if (this.environment instanceof ConfigurableEnvironment configurableEnvironment) {
addLocalManagementPortPropertyAlias(configurableEnvironment);
}
}

@ -173,8 +173,8 @@ class ServletManagementChildContextConfiguration {
private AccessLogValve findAccessLogValve(TomcatServletWebServerFactory factory) {
for (Valve engineValve : factory.getEngineValves()) {
if (engineValve instanceof AccessLogValve) {
return (AccessLogValve) engineValve;
if (engineValve instanceof AccessLogValve accessLogValve) {
return accessLogValve;
}
}
return null;
@ -202,14 +202,14 @@ class ServletManagementChildContextConfiguration {
private void customizeServer(Server server) {
RequestLog requestLog = server.getRequestLog();
if (requestLog instanceof CustomRequestLog) {
customizeRequestLog((CustomRequestLog) requestLog);
if (requestLog instanceof CustomRequestLog customRequestLog) {
customizeRequestLog(customRequestLog);
}
}
private void customizeRequestLog(CustomRequestLog requestLog) {
if (requestLog.getWriter() instanceof RequestLogWriter) {
customizeRequestLogWriter((RequestLogWriter) requestLog.getWriter());
if (requestLog.getWriter() instanceof RequestLogWriter requestLogWriter) {
customizeRequestLogWriter(requestLogWriter);
}
}

@ -341,9 +341,9 @@ class DataSourcePoolMetricsAutoConfigurationTests {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof HikariDataSource) {
if (bean instanceof HikariDataSource dataSource) {
try {
((HikariDataSource) bean).getConnection().close();
dataSource.getConnection().close();
}
catch (SQLException ex) {
throw new IllegalStateException(ex);

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -64,8 +64,8 @@ public class BeansEndpoint {
private static ConfigurableApplicationContext getConfigurableParent(ConfigurableApplicationContext context) {
ApplicationContext parent = context.getParent();
if (parent instanceof ConfigurableApplicationContext) {
return (ConfigurableApplicationContext) parent;
if (parent instanceof ConfigurableApplicationContext configurableParent) {
return configurableParent;
}
return null;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -72,8 +72,8 @@ public class ShutdownEndpoint implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (context instanceof ConfigurableApplicationContext) {
this.context = (ConfigurableApplicationContext) context;
if (context instanceof ConfigurableApplicationContext configurableContext) {
this.context = configurableContext;
}
}

@ -434,9 +434,9 @@ public class ConfigurationPropertiesReportEndpoint implements ApplicationContext
@Override
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider,
PropertyWriter writer) throws Exception {
if (writer instanceof BeanPropertyWriter) {
if (writer instanceof BeanPropertyWriter beanPropertyWriter) {
try {
if (pojo == ((BeanPropertyWriter) writer).get(pojo)) {
if (pojo == beanPropertyWriter.get(pojo)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping '" + writer.getFullName() + "' on '" + pojo.getClass().getName()
+ "' as it is self-referential");

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -70,11 +70,11 @@ public class EndpointLinksResolver {
Map<String, Link> links = new LinkedHashMap<>();
links.put("self", new Link(normalizedUrl));
for (ExposableEndpoint<?> endpoint : this.endpoints) {
if (endpoint instanceof ExposableWebEndpoint) {
collectLinks(links, (ExposableWebEndpoint) endpoint, normalizedUrl);
if (endpoint instanceof ExposableWebEndpoint exposableWebEndpoint) {
collectLinks(links, exposableWebEndpoint, normalizedUrl);
}
else if (endpoint instanceof PathMappedEndpoint) {
String rootPath = ((PathMappedEndpoint) endpoint).getRootPath();
else if (endpoint instanceof PathMappedEndpoint pathMappedEndpoint) {
String rootPath = pathMappedEndpoint.getRootPath();
Link link = createLink(normalizedUrl, rootPath);
links.put(endpoint.getEndpointId().toLowerCaseString(), link);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -66,8 +66,8 @@ public class PathMappedEndpoints implements Iterable<PathMappedEndpoint> {
private Map<EndpointId, PathMappedEndpoint> getEndpoints(Collection<EndpointsSupplier<?>> suppliers) {
Map<EndpointId, PathMappedEndpoint> endpoints = new LinkedHashMap<>();
suppliers.forEach((supplier) -> supplier.getEndpoints().forEach((endpoint) -> {
if (endpoint instanceof PathMappedEndpoint) {
endpoints.put(endpoint.getEndpointId(), (PathMappedEndpoint) endpoint);
if (endpoint instanceof PathMappedEndpoint pathMappedEndpoint) {
endpoints.put(endpoint.getEndpointId(), pathMappedEndpoint);
}
}));
return Collections.unmodifiableMap(endpoints);

@ -176,15 +176,15 @@ public class EnvironmentEndpoint {
}
private MutablePropertySources getPropertySources() {
if (this.environment instanceof ConfigurableEnvironment) {
return ((ConfigurableEnvironment) this.environment).getPropertySources();
if (this.environment instanceof ConfigurableEnvironment configurableEnvironment) {
return configurableEnvironment.getPropertySources();
}
return new StandardEnvironment().getPropertySources();
}
private void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) {
if (source instanceof CompositePropertySource) {
for (PropertySource<?> nest : ((CompositePropertySource) source).getPropertySources()) {
if (source instanceof CompositePropertySource compositePropertySource) {
for (PropertySource<?> nest : compositePropertySource.getPropertySources()) {
extract(source.getName() + ":", map, nest);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -88,10 +88,10 @@ public abstract class AbstractHealthIndicator implements HealthIndicator {
return builder.build();
}
private void logExceptionIfPresent(Throwable ex) {
if (ex != null && this.logger.isWarnEnabled()) {
String message = (ex instanceof Exception) ? this.healthCheckFailedMessage.apply((Exception) ex) : null;
this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE, ex);
private void logExceptionIfPresent(Throwable throwable) {
if (throwable != null && this.logger.isWarnEnabled()) {
String message = (throwable instanceof Exception ex) ? this.healthCheckFailedMessage.apply(ex) : null;
this.logger.warn(StringUtils.hasText(message) ? message : DEFAULT_MESSAGE, throwable);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -106,8 +106,7 @@ public final class Health extends HealthComponent {
if (obj == this) {
return true;
}
if (obj instanceof Health) {
Health other = (Health) obj;
if (obj instanceof Health other) {
return this.status.equals(other.status) && this.details.equals(other.details);
}
return false;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -33,11 +33,11 @@ public interface ReactiveHealthContributor {
static ReactiveHealthContributor adapt(HealthContributor healthContributor) {
Assert.notNull(healthContributor, "HealthContributor must not be null");
if (healthContributor instanceof HealthIndicator) {
return new HealthIndicatorReactiveAdapter((HealthIndicator) healthContributor);
if (healthContributor instanceof HealthIndicator healthIndicator) {
return new HealthIndicatorReactiveAdapter(healthIndicator);
}
if (healthContributor instanceof CompositeHealthContributor) {
return new CompositeHealthContributorReactiveAdapter((CompositeHealthContributor) healthContributor);
if (healthContributor instanceof CompositeHealthContributor compositeHealthContributor) {
return new CompositeHealthContributorReactiveAdapter(compositeHealthContributor);
}
throw new IllegalStateException("Unknown HealthContributor type");
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -107,8 +107,8 @@ public final class Status {
if (obj == this) {
return true;
}
if (obj instanceof Status) {
return ObjectUtils.nullSafeEquals(this.code, ((Status) obj).code);
if (obj instanceof Status other) {
return ObjectUtils.nullSafeEquals(this.code, other.code);
}
return false;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -71,8 +71,7 @@ public final class Info {
if (obj == this) {
return true;
}
if (obj instanceof Info) {
Info other = (Info) obj;
if (obj instanceof Info other) {
return this.details.equals(other.details);
}
return false;

@ -64,8 +64,8 @@ public class MetricsEndpoint {
}
private void collectNames(Set<String> names, MeterRegistry registry) {
if (registry instanceof CompositeMeterRegistry) {
((CompositeMeterRegistry) registry).getRegistries().forEach((member) -> collectNames(names, member));
if (registry instanceof CompositeMeterRegistry compositeMeterRegistry) {
compositeMeterRegistry.getRegistries().forEach((member) -> collectNames(names, member));
}
else {
registry.getMeters().stream().map(this::getName).forEach(names::add);
@ -109,8 +109,8 @@ public class MetricsEndpoint {
}
private Collection<Meter> findFirstMatchingMeters(MeterRegistry registry, String name, Iterable<Tag> tags) {
if (registry instanceof CompositeMeterRegistry) {
return findFirstMatchingMeters((CompositeMeterRegistry) registry, name, tags);
if (registry instanceof CompositeMeterRegistry compositeMeterRegistry) {
return findFirstMatchingMeters(compositeMeterRegistry, name, tags);
}
return registry.find(name).tags(tags).meters();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -98,8 +98,8 @@ public class CacheMetricsRegistrar {
private static Cache unwrapIfNecessary(Cache cache) {
try {
if (cache instanceof TransactionAwareCacheDecorator) {
return ((TransactionAwareCacheDecorator) cache).getTargetCache();
if (cache instanceof TransactionAwareCacheDecorator decorator) {
return decorator.getTargetCache();
}
}
catch (NoClassDefFoundError ex) {

@ -136,8 +136,8 @@ public class PrometheusPushGatewayManager {
}
private void shutdown(ShutdownOperation shutdownOperation) {
if (this.scheduler instanceof PushGatewayTaskScheduler) {
((PushGatewayTaskScheduler) this.scheduler).shutdown();
if (this.scheduler instanceof PushGatewayTaskScheduler pushGatewayTaskScheduler) {
pushGatewayTaskScheduler.shutdown();
}
this.scheduled.cancel(false);
switch (shutdownOperation) {

@ -94,11 +94,11 @@ public class StartupTimeMetricsListener implements SmartApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationStartedEvent) {
onApplicationStarted((ApplicationStartedEvent) event);
if (event instanceof ApplicationStartedEvent startedEvent) {
onApplicationStarted(startedEvent);
}
if (event instanceof ApplicationReadyEvent) {
onApplicationReady((ApplicationReadyEvent) event);
if (event instanceof ApplicationReadyEvent readyEvent) {
onApplicationReady(readyEvent);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -105,8 +105,8 @@ class MetricsClientHttpRequestInterceptor implements ClientHttpRequestIntercepto
}
UriTemplateHandler createUriTemplateHandler(UriTemplateHandler delegate) {
if (delegate instanceof RootUriTemplateHandler) {
return ((RootUriTemplateHandler) delegate).withHandlerWrapper(CapturingUriTemplateHandler::new);
if (delegate instanceof RootUriTemplateHandler rootHandler) {
return rootHandler.withHandlerWrapper(CapturingUriTemplateHandler::new);
}
return new CapturingUriTemplateHandler(delegate);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -42,10 +42,10 @@ public abstract class AbstractJettyMetricsBinder implements ApplicationListener<
}
private Server findServer(ApplicationContext applicationContext) {
if (applicationContext instanceof WebServerApplicationContext) {
WebServer webServer = ((WebServerApplicationContext) applicationContext).getWebServer();
if (webServer instanceof JettyWebServer) {
return ((JettyWebServer) webServer).getServer();
if (applicationContext instanceof WebServerApplicationContext webServerApplicationContext) {
WebServer webServer = webServerApplicationContext.getWebServer();
if (webServer instanceof JettyWebServer jettyWebServer) {
return jettyWebServer.getServer();
}
}
return null;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -118,8 +118,7 @@ public class MetricsWebFilter implements WebFilter {
}
private Set<Timed> getTimedAnnotations(Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handler instanceof HandlerMethod handlerMethod) {
return TimedAnnotations.get(handlerMethod.getMethod(), handlerMethod.getBeanType());
}
return Collections.emptySet();

@ -109,10 +109,10 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor {
}
private Set<Timed> getTimedAnnotations(Object handler) {
if (!(handler instanceof HandlerMethod)) {
return Collections.emptySet();
if (handler instanceof HandlerMethod handlerMethod) {
return getTimedAnnotations(handlerMethod);
}
return getTimedAnnotations((HandlerMethod) handler);
return Collections.emptySet();
}
private Set<Timed> getTimedAnnotations(HandlerMethod handler) {

@ -147,8 +147,7 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter {
}
private Set<Timed> getTimedAnnotations(Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handler instanceof HandlerMethod handlerMethod) {
return TimedAnnotations.get(handlerMethod.getMethod(), handlerMethod.getBeanType());
}
return Collections.emptySet();

@ -65,10 +65,10 @@ public class TomcatMetricsBinder implements ApplicationListener<ApplicationStart
}
private Manager findManager(ApplicationContext applicationContext) {
if (applicationContext instanceof WebServerApplicationContext) {
WebServer webServer = ((WebServerApplicationContext) applicationContext).getWebServer();
if (webServer instanceof TomcatWebServer) {
Context context = findContext((TomcatWebServer) webServer);
if (applicationContext instanceof WebServerApplicationContext webServerApplicationContext) {
WebServer webServer = webServerApplicationContext.getWebServer();
if (webServer instanceof TomcatWebServer tomcatWebServer) {
Context context = findContext(tomcatWebServer);
if (context != null) {
return context.getManager();
}
@ -79,8 +79,8 @@ public class TomcatMetricsBinder implements ApplicationListener<ApplicationStart
private Context findContext(TomcatWebServer tomcatWebServer) {
for (Container container : tomcatWebServer.getTomcat().getHost().findChildren()) {
if (container instanceof Context) {
return (Context) container;
if (container instanceof Context context) {
return context;
}
}
return null;

@ -56,8 +56,8 @@ public class RedisHealthIndicator extends AbstractHealthIndicator {
}
private void doHealthCheck(Health.Builder builder, RedisConnection connection) {
if (connection instanceof RedisClusterConnection) {
RedisHealth.fromClusterInfo(builder, ((RedisClusterConnection) connection).clusterGetClusterInfo());
if (connection instanceof RedisClusterConnection clusterConnection) {
RedisHealth.fromClusterInfo(builder, clusterConnection.clusterGetClusterInfo());
}
else {
RedisHealth.up(builder, connection.serverCommands().info());

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,9 +63,8 @@ public class RedisReactiveHealthIndicator extends AbstractReactiveHealthIndicato
}
private Mono<Health> getHealth(Health.Builder builder, ReactiveRedisConnection connection) {
if (connection instanceof ReactiveRedisClusterConnection) {
return ((ReactiveRedisClusterConnection) connection).clusterGetClusterInfo()
.map((info) -> fromClusterInfo(builder, info));
if (connection instanceof ReactiveRedisClusterConnection clusterConnection) {
return clusterConnection.clusterGetClusterInfo().map((info) -> fromClusterInfo(builder, info));
}
return connection.serverCommands().info("server").map((info) -> up(builder, info));
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -130,11 +130,10 @@ public class ScheduledTasksEndpoint {
private static TaskDescription describeTriggerTask(TriggerTask triggerTask) {
Trigger trigger = triggerTask.getTrigger();
if (trigger instanceof CronTrigger) {
return new CronTaskDescription(triggerTask, (CronTrigger) trigger);
if (trigger instanceof CronTrigger cronTrigger) {
return new CronTaskDescription(triggerTask, cronTrigger);
}
if (trigger instanceof PeriodicTrigger) {
PeriodicTrigger periodicTrigger = (PeriodicTrigger) trigger;
if (trigger instanceof PeriodicTrigger periodicTrigger) {
if (periodicTrigger.isFixedRate()) {
return new FixedRateTaskDescription(triggerTask, periodicTrigger);
}
@ -275,8 +274,8 @@ public class ScheduledTasksEndpoint {
private final String target;
private RunnableDescription(Runnable runnable) {
if (runnable instanceof ScheduledMethodRunnable) {
Method method = ((ScheduledMethodRunnable) runnable).getMethod();
if (runnable instanceof ScheduledMethodRunnable scheduledMethodRunnable) {
Method method = scheduledMethodRunnable.getMethod();
this.target = method.getDeclaringClass().getName() + "." + method.getName();
}
else {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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,14 +63,14 @@ public class AuthenticationAuditListener extends AbstractAuthenticationAuditList
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
if (event instanceof AbstractAuthenticationFailureEvent) {
onAuthenticationFailureEvent((AbstractAuthenticationFailureEvent) event);
if (event instanceof AbstractAuthenticationFailureEvent failureEvent) {
onAuthenticationFailureEvent(failureEvent);
}
else if (this.webListener != null && this.webListener.accepts(event)) {
this.webListener.process(this, event);
}
else if (event instanceof AuthenticationSuccessEvent) {
onAuthenticationSuccessEvent((AuthenticationSuccessEvent) event);
else if (event instanceof AuthenticationSuccessEvent successEvent) {
onAuthenticationSuccessEvent(successEvent);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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,11 +40,11 @@ public class AuthorizationAuditListener extends AbstractAuthorizationAuditListen
@Override
public void onApplicationEvent(AbstractAuthorizationEvent event) {
if (event instanceof AuthenticationCredentialsNotFoundEvent) {
onAuthenticationCredentialsNotFoundEvent((AuthenticationCredentialsNotFoundEvent) event);
if (event instanceof AuthenticationCredentialsNotFoundEvent credentialsNotFoundEvent) {
onAuthenticationCredentialsNotFoundEvent(credentialsNotFoundEvent);
}
else if (event instanceof AuthorizationFailureEvent) {
onAuthorizationFailureEvent((AuthorizationFailureEvent) event);
else if (event instanceof AuthorizationFailureEvent authorizationFailureEvent) {
onAuthorizationFailureEvent(authorizationFailureEvent);
}
}

@ -66,15 +66,15 @@ final class DispatcherServletHandlerMappings {
}
private void initializeDispatcherServletIfPossible() {
if (!(this.applicationContext instanceof ServletWebServerApplicationContext)) {
if (!(this.applicationContext instanceof ServletWebServerApplicationContext webServerApplicationContext)) {
return;
}
WebServer webServer = ((ServletWebServerApplicationContext) this.applicationContext).getWebServer();
if (webServer instanceof UndertowServletWebServer) {
new UndertowServletInitializer((UndertowServletWebServer) webServer).initializeServlet(this.name);
WebServer webServer = webServerApplicationContext.getWebServer();
if (webServer instanceof UndertowServletWebServer undertowServletWebServer) {
new UndertowServletInitializer(undertowServletWebServer).initializeServlet(this.name);
}
else if (webServer instanceof TomcatWebServer) {
new TomcatServletInitializer((TomcatWebServer) webServer).initializeServlet(this.name);
else if (webServer instanceof TomcatWebServer tomcatWebServer) {
new TomcatServletInitializer(tomcatWebServer).initializeServlet(this.name);
}
}
@ -101,9 +101,8 @@ final class DispatcherServletHandlerMappings {
private void initializeServlet(Context context, String name) {
Container child = context.findChild(name);
if (child instanceof StandardWrapper) {
if (child instanceof StandardWrapper wrapper) {
try {
StandardWrapper wrapper = (StandardWrapper) child;
wrapper.deallocate(wrapper.allocate());
}
catch (ServletException ex) {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -68,8 +68,8 @@ public class DispatcherServletsMappingDescriptionProvider implements MappingDesc
@Override
public Map<String, List<DispatcherServletMappingDescription>> describeMappings(ApplicationContext context) {
if (context instanceof WebApplicationContext) {
return describeMappings((WebApplicationContext) context);
if (context instanceof WebApplicationContext webApplicationContext) {
return describeMappings(webApplicationContext);
}
return Collections.emptyMap();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -38,12 +38,12 @@ public class FiltersMappingDescriptionProvider implements MappingDescriptionProv
@Override
public List<FilterRegistrationMappingDescription> describeMappings(ApplicationContext context) {
if (!(context instanceof WebApplicationContext)) {
return Collections.emptyList();
}
return ((WebApplicationContext) context).getServletContext().getFilterRegistrations().values().stream()
if (context instanceof WebApplicationContext webApplicationContext) {
return webApplicationContext.getServletContext().getFilterRegistrations().values().stream()
.map(FilterRegistrationMappingDescription::new).collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public String getMappingName() {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -38,12 +38,12 @@ public class ServletsMappingDescriptionProvider implements MappingDescriptionPro
@Override
public List<ServletRegistrationMappingDescription> describeMappings(ApplicationContext context) {
if (!(context instanceof WebApplicationContext)) {
return Collections.emptyList();
}
return ((WebApplicationContext) context).getServletContext().getServletRegistrations().values().stream()
if (context instanceof WebApplicationContext webApplicationContext) {
return webApplicationContext.getServletContext().getServletRegistrations().values().stream()
.map(ServletRegistrationMappingDescription::new).collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public String getMappingName() {

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -183,8 +183,8 @@ class WebEndpointTestInvocationContextProvider implements TestTemplateInvocation
}
private int determinePort() {
if (this.context instanceof AnnotationConfigServletWebServerApplicationContext) {
return ((AnnotationConfigServletWebServerApplicationContext) this.context).getWebServer().getPort();
if (this.context instanceof AnnotationConfigServletWebServerApplicationContext webServerContext) {
return webServerContext.getWebServer().getPort();
}
return this.context.getBean(PortHolder.class).getPort();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -139,8 +139,8 @@ public abstract class AbstractDependsOnBeanFactoryPostProcessor implements BeanF
}
catch (NoSuchBeanDefinitionException ex) {
BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
if (parentBeanFactory instanceof ConfigurableListableBeanFactory) {
return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory);
if (parentBeanFactory instanceof ConfigurableListableBeanFactory listableBeanFactory) {
return getBeanDefinition(beanName, listableBeanFactory);
}
throw ex;
}

@ -300,17 +300,17 @@ public class AutoConfigurationImportSelector implements DeferredImportSelector,
private void invokeAwareMethods(Object instance) {
if (instance instanceof Aware) {
if (instance instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) instance).setBeanClassLoader(this.beanClassLoader);
if (instance instanceof BeanClassLoaderAware beanClassLoaderAwareInstance) {
beanClassLoaderAwareInstance.setBeanClassLoader(this.beanClassLoader);
}
if (instance instanceof BeanFactoryAware) {
((BeanFactoryAware) instance).setBeanFactory(this.beanFactory);
if (instance instanceof BeanFactoryAware beanFactoryAwareInstance) {
beanFactoryAwareInstance.setBeanFactory(this.beanFactory);
}
if (instance instanceof EnvironmentAware) {
((EnvironmentAware) instance).setEnvironment(this.environment);
if (instance instanceof EnvironmentAware environmentAwareInstance) {
environmentAwareInstance.setEnvironment(this.environment);
}
if (instance instanceof ResourceLoaderAware) {
((ResourceLoaderAware) instance).setResourceLoader(this.resourceLoader);
if (instance instanceof ResourceLoaderAware resourceLoaderAwareInstance) {
resourceLoaderAwareInstance.setResourceLoader(this.resourceLoader);
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -117,8 +117,8 @@ class SharedMetadataReaderFactoryContextInitializer
}
private void configureConfigurationClassPostProcessor(BeanDefinition definition) {
if (definition instanceof AbstractBeanDefinition) {
configureConfigurationClassPostProcessor((AbstractBeanDefinition) definition);
if (definition instanceof AbstractBeanDefinition abstractBeanDefinition) {
configureConfigurationClassPostProcessor(abstractBeanDefinition);
return;
}
configureConfigurationClassPostProcessor(definition.getPropertyValues());
@ -159,8 +159,8 @@ class SharedMetadataReaderFactoryContextInitializer
@Override
public Object get() {
Object instance = this.instanceSupplier.get();
if (instance instanceof ConfigurationClassPostProcessor) {
configureConfigurationClassPostProcessor((ConfigurationClassPostProcessor) instance);
if (instance instanceof ConfigurationClassPostProcessor postProcessor) {
configureConfigurationClassPostProcessor(postProcessor);
}
return instance;
}

@ -77,8 +77,7 @@ public class AopAutoConfiguration {
@Bean
static BeanFactoryPostProcessor forceAutoProxyCreatorToUseClassProxying() {
return (beanFactory) -> {
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
if (beanFactory instanceof BeanDefinitionRegistry registry) {
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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,8 +40,8 @@ class CacheCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String sourceClass = "";
if (metadata instanceof ClassMetadata) {
sourceClass = ((ClassMetadata) metadata).getClassName();
if (metadata instanceof ClassMetadata classMetadata) {
sourceClass = classMetadata.getClassName();
}
ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass);
Environment environment = context.getEnvironment();

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -132,8 +132,9 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem
private void validateMemberCondition(Condition condition, ConfigurationPhase nestedPhase,
String nestedClassName) {
if (nestedPhase == ConfigurationPhase.PARSE_CONFIGURATION && condition instanceof ConfigurationCondition) {
ConfigurationPhase memberPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
if (nestedPhase == ConfigurationPhase.PARSE_CONFIGURATION
&& condition instanceof ConfigurationCondition configurationCondition) {
ConfigurationPhase memberPhase = configurationCondition.getConfigurationPhase();
if (memberPhase == ConfigurationPhase.REGISTER_BEAN) {
throw new IllegalStateException("Nested condition " + nestedClassName + " uses a configuration "
+ "phase that is inappropriate for " + condition.getClass());
@ -190,8 +191,8 @@ public abstract class AbstractNestedCondition extends SpringBootCondition implem
}
private ConditionOutcome getConditionOutcome(AnnotationMetadata metadata, Condition condition) {
if (condition instanceof SpringBootCondition) {
return ((SpringBootCondition) condition).getMatchOutcome(this.context, metadata);
if (condition instanceof SpringBootCondition springBootCondition) {
return springBootCondition.getMatchOutcome(this.context, metadata);
}
return new ConditionOutcome(condition.matches(this.context, metadata), ConditionMessage.empty());
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,8 +45,8 @@ class ConditionEvaluationReportAutoConfigurationImportListener
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (beanFactory instanceof ConfigurableListableBeanFactory)
? (ConfigurableListableBeanFactory) beanFactory : null;
this.beanFactory = (beanFactory instanceof ConfigurableListableBeanFactory listableBeanFactory)
? listableBeanFactory : null;
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,13 +61,13 @@ public final class ConditionMessage {
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ConditionMessage)) {
return false;
}
if (obj == this) {
return true;
}
return ObjectUtils.nullSafeEquals(((ConditionMessage) obj).message, this.message);
if (obj instanceof ConditionMessage other) {
return ObjectUtils.nullSafeEquals(other.message, this.message);
}
return false;
}
@Override

@ -252,11 +252,11 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat
ResolvableType generic = ResolvableType.forClassWithGenerics(container, type);
result = addAll(result, beanFactory.getBeanNamesForType(generic, true, false));
}
if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory) {
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory();
if (parent instanceof ListableBeanFactory) {
result = collectBeanNamesForType((ListableBeanFactory) parent, considerHierarchy, type,
parameterizedContainers, result);
if (considerHierarchy && beanFactory instanceof HierarchicalBeanFactory hierarchicalBeanFactory) {
BeanFactory parent = hierarchicalBeanFactory.getParentBeanFactory();
if (parent instanceof ListableBeanFactory listableBeanFactory) {
result = collectBeanNamesForType(listableBeanFactory, considerHierarchy, type, parameterizedContainers,
result);
}
}
return result;
@ -286,9 +286,8 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat
result = addAll(result, beanFactory.getBeanNamesForAnnotation(annotationType));
if (considerHierarchy) {
BeanFactory parent = ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory();
if (parent instanceof ListableBeanFactory) {
result = collectBeanNamesForAnnotation((ListableBeanFactory) parent, annotationType, considerHierarchy,
result);
if (parent instanceof ListableBeanFactory listableBeanFactory) {
result = collectBeanNamesForAnnotation(listableBeanFactory, annotationType, considerHierarchy, result);
}
}
return result;
@ -370,9 +369,9 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat
if (beanFactory.containsBeanDefinition(beanName)) {
return beanFactory.getBeanDefinition(beanName);
}
if (considerHierarchy && beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
return findBeanDefinition(((ConfigurableListableBeanFactory) beanFactory.getParentBeanFactory()), beanName,
considerHierarchy);
if (considerHierarchy
&& beanFactory.getParentBeanFactory() instanceof ConfigurableListableBeanFactory listableBeanFactory) {
return findBeanDefinition(listableBeanFactory, beanName, considerHierarchy);
}
return null;
}
@ -455,11 +454,11 @@ class OnBeanCondition extends FilteringSpringBootCondition implements Configurat
for (String attributeName : attributeNames) {
List<Object> values = attributes.getOrDefault(attributeName, Collections.emptyList());
for (Object value : values) {
if (value instanceof String[]) {
merge(result, (String[]) value);
if (value instanceof String[] stringArray) {
merge(result, stringArray);
}
else if (value instanceof String) {
merge(result, (String) value);
else if (value instanceof String string) {
merge(result, string);
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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,8 +35,7 @@ class OnWarDeploymentCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ResourceLoader resourceLoader = context.getResourceLoader();
if (resourceLoader instanceof WebApplicationContext) {
WebApplicationContext applicationContext = (WebApplicationContext) resourceLoader;
if (resourceLoader instanceof WebApplicationContext applicationContext) {
ServletContext servletContext = applicationContext.getServletContext();
if (servletContext != null) {
return ConditionOutcome.match("Application is deployed as a WAR file.");

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -62,19 +62,17 @@ public abstract class SpringBootCondition implements Condition {
}
private String getName(AnnotatedTypeMetadata metadata) {
if (metadata instanceof AnnotationMetadata) {
return ((AnnotationMetadata) metadata).getClassName();
if (metadata instanceof AnnotationMetadata annotationMetadata) {
return annotationMetadata.getClassName();
}
if (metadata instanceof MethodMetadata) {
MethodMetadata methodMetadata = (MethodMetadata) metadata;
if (metadata instanceof MethodMetadata methodMetadata) {
return methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName();
}
return metadata.toString();
}
private static String getClassOrMethodName(AnnotatedTypeMetadata metadata) {
if (metadata instanceof ClassMetadata) {
ClassMetadata classMetadata = (ClassMetadata) metadata;
if (metadata instanceof ClassMetadata classMetadata) {
return classMetadata.getClassName();
}
MethodMetadata methodMetadata = (MethodMetadata) metadata;
@ -141,8 +139,8 @@ public abstract class SpringBootCondition implements Condition {
* @return {@code true} if the condition matches.
*/
protected final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata, Condition condition) {
if (condition instanceof SpringBootCondition) {
return ((SpringBootCondition) condition).getMatchOutcome(context, metadata).isMatch();
if (condition instanceof SpringBootCondition springBootCondition) {
return springBootCondition.getMatchOutcome(context, metadata).isMatch();
}
return condition.matches(context, metadata);
}

@ -142,8 +142,8 @@ class NoSuchBeanDefinitionFailureAnalyzer extends AbstractInjectionFailureAnalyz
private MethodMetadata getFactoryMethodMetadata(String beanName) {
BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition(beanName);
if (beanDefinition instanceof AnnotatedBeanDefinition) {
return ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata();
if (beanDefinition instanceof AnnotatedBeanDefinition annotatedBeanDefinition) {
return annotatedBeanDefinition.getFactoryMethodMetadata();
}
return null;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -129,8 +129,8 @@ public class HttpMessageConverters implements Iterable<HttpMessageConverter<?>>
}
}
combined.add(defaultConverter);
if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter) {
configurePartConverters((AllEncompassingFormHttpMessageConverter) defaultConverter, converters);
if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter allEncompassingConverter) {
configurePartConverters(allEncompassingConverter, converters);
}
}
combined.addAll(0, processing);

@ -143,9 +143,8 @@ public class EmbeddedLdapAutoConfiguration {
}
private void setPortProperty(ApplicationContext context, int port) {
if (context instanceof ConfigurableApplicationContext) {
MutablePropertySources sources = ((ConfigurableApplicationContext) context).getEnvironment()
.getPropertySources();
if (context instanceof ConfigurableApplicationContext configurableContext) {
MutablePropertySources sources = configurableContext.getEnvironment().getPropertySources();
getLdapPorts(sources).put("local.ldap.port", port);
}
if (context.getParent() != null) {

@ -25,7 +25,6 @@ import org.springframework.boot.logging.LogLevel;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.context.support.GenericApplicationContext;
@ -101,13 +100,13 @@ public class ConditionEvaluationReportLoggingListener
protected void onApplicationEvent(ApplicationEvent event) {
ConfigurableApplicationContext initializerApplicationContext = this.applicationContext;
if (event instanceof ContextRefreshedEvent) {
if (((ApplicationContextEvent) event).getApplicationContext() == initializerApplicationContext) {
if (event instanceof ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext() == initializerApplicationContext) {
logAutoConfigurationReport();
}
}
else if (event instanceof ApplicationFailedEvent
&& ((ApplicationFailedEvent) event).getApplicationContext() == initializerApplicationContext) {
else if (event instanceof ApplicationFailedEvent applicationFailedEvent
&& applicationFailedEvent.getApplicationContext() == initializerApplicationContext) {
logAutoConfigurationReport(true);
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -50,8 +50,8 @@ class PrimaryDefaultValidatorPostProcessor implements ImportBeanDefinitionRegist
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
if (beanFactory instanceof ConfigurableListableBeanFactory listableBeanFactory) {
this.beanFactory = listableBeanFactory;
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -73,22 +73,22 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (!this.existingBean && this.target instanceof ApplicationContextAware) {
((ApplicationContextAware) this.target).setApplicationContext(applicationContext);
if (!this.existingBean && this.target instanceof ApplicationContextAware contextAwareTarget) {
contextAwareTarget.setApplicationContext(applicationContext);
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (!this.existingBean && this.target instanceof InitializingBean) {
((InitializingBean) this.target).afterPropertiesSet();
if (!this.existingBean && this.target instanceof InitializingBean initializingBean) {
initializingBean.afterPropertiesSet();
}
}
@Override
public void destroy() throws Exception {
if (!this.existingBean && this.target instanceof DisposableBean) {
((DisposableBean) this.target).destroy();
if (!this.existingBean && this.target instanceof DisposableBean disposableBean) {
disposableBean.destroy();
}
}
@ -120,11 +120,11 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware
private static Validator getExisting(ApplicationContext applicationContext) {
try {
jakarta.validation.Validator validator = applicationContext.getBean(jakarta.validation.Validator.class);
if (validator instanceof Validator) {
return (Validator) validator;
jakarta.validation.Validator validatorBean = applicationContext.getBean(jakarta.validation.Validator.class);
if (validatorBean instanceof Validator validator) {
return validator;
}
return new SpringValidatorAdapter(validator);
return new SpringValidatorAdapter(validatorBean);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
@ -144,12 +144,11 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware
}
private static Validator wrap(Validator validator, boolean existingBean) {
if (validator instanceof jakarta.validation.Validator) {
if (validator instanceof SpringValidatorAdapter) {
return new ValidatorAdapter((SpringValidatorAdapter) validator, existingBean);
if (validator instanceof jakarta.validation.Validator jakartaValidator) {
if (jakartaValidator instanceof SpringValidatorAdapter adapter) {
return new ValidatorAdapter(adapter, existingBean);
}
return new ValidatorAdapter(new SpringValidatorAdapter((jakarta.validation.Validator) validator),
existingBean);
return new ValidatorAdapter(new SpringValidatorAdapter(jakartaValidator), existingBean);
}
return validator;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -108,8 +108,8 @@ public class JettyWebServerFactoryCustomizer
private void customizeIdleTimeout(ConfigurableJettyWebServerFactory factory, Duration connectionTimeout) {
factory.addServerCustomizers((server) -> {
for (org.eclipse.jetty.server.Connector connector : server.getConnectors()) {
if (connector instanceof AbstractConnector) {
((AbstractConnector) connector).setIdleTimeout(connectionTimeout.toMillis());
if (connector instanceof AbstractConnector abstractConnector) {
abstractConnector.setIdleTimeout(connectionTimeout.toMillis());
}
}
});
@ -125,14 +125,14 @@ public class JettyWebServerFactoryCustomizer
private void setHandlerMaxHttpFormPostSize(Handler... handlers) {
for (Handler handler : handlers) {
if (handler instanceof ContextHandler) {
((ContextHandler) handler).setMaxFormContentSize(maxHttpFormPostSize);
if (handler instanceof ContextHandler contextHandler) {
contextHandler.setMaxFormContentSize(maxHttpFormPostSize);
}
else if (handler instanceof HandlerWrapper) {
setHandlerMaxHttpFormPostSize(((HandlerWrapper) handler).getHandler());
else if (handler instanceof HandlerWrapper wrapper) {
setHandlerMaxHttpFormPostSize(wrapper.getHandler());
}
else if (handler instanceof HandlerCollection) {
setHandlerMaxHttpFormPostSize(((HandlerCollection) handler).getHandlers());
else if (handler instanceof HandlerCollection collection) {
setHandlerMaxHttpFormPostSize(collection.getHandlers());
}
}
}

@ -152,8 +152,8 @@ public class TomcatWebServerFactoryCustomizer
factory.addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler();
for (UpgradeProtocol upgradeProtocol : handler.findUpgradeProtocols()) {
if (upgradeProtocol instanceof Http2Protocol) {
((Http2Protocol) upgradeProtocol).setKeepAliveTimeout(keepAliveTimeout.toMillis());
if (upgradeProtocol instanceof Http2Protocol protocol) {
protocol.setKeepAliveTimeout(keepAliveTimeout.toMillis());
}
}
if (handler instanceof AbstractProtocol) {

@ -52,8 +52,7 @@ public class ReactiveMultipartAutoConfiguration {
@Order(0)
CodecCustomizer defaultPartHttpMessageReaderCustomizer(ReactiveMultipartProperties multipartProperties) {
return (configurer) -> configurer.defaultCodecs().configureDefaultCodec((codec) -> {
if (codec instanceof DefaultPartHttpMessageReader) {
DefaultPartHttpMessageReader defaultPartHttpMessageReader = (DefaultPartHttpMessageReader) codec;
if (codec instanceof DefaultPartHttpMessageReader defaultPartHttpMessageReader) {
PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
map.from(multipartProperties::getMaxInMemorySize).asInt(DataSize::toBytes)
.to(defaultPartHttpMessageReader::setMaxInMemorySize);

@ -90,8 +90,8 @@ public class ReactiveWebServerFactoryAutoConfiguration {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
if (beanFactory instanceof ConfigurableListableBeanFactory listableBeanFactory) {
this.beanFactory = listableBeanFactory;
}
}

@ -129,8 +129,8 @@ public class ServletWebServerFactoryAutoConfiguration {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
if (beanFactory instanceof ConfigurableListableBeanFactory listableBeanFactory) {
this.beanFactory = listableBeanFactory;
}
}

@ -237,8 +237,8 @@ public class WebMvcAutoConfiguration {
if (this.beanFactory.containsBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)) {
Object taskExecutor = this.beanFactory
.getBean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
if (taskExecutor instanceof AsyncTaskExecutor) {
configurer.setTaskExecutor(((AsyncTaskExecutor) taskExecutor));
if (taskExecutor instanceof AsyncTaskExecutor asyncTaskExecutor) {
configurer.setTaskExecutor(asyncTaskExecutor);
}
}
Duration timeout = this.mvcProperties.getAsync().getRequestTimeout();
@ -559,8 +559,8 @@ public class WebMvcAutoConfiguration {
super.extendHandlerExceptionResolvers(exceptionResolvers);
if (this.mvcProperties.isLogResolvedException()) {
for (HandlerExceptionResolver resolver : exceptionResolvers) {
if (resolver instanceof AbstractHandlerExceptionResolver) {
((AbstractHandlerExceptionResolver) resolver).setWarnLogCategory(resolver.getClass().getName());
if (resolver instanceof AbstractHandlerExceptionResolver abstractResolver) {
abstractResolver.setWarnLogCategory(resolver.getClass().getName());
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -91,8 +91,8 @@ class AbstractDependsOnBeanFactoryPostProcessorTests {
}
catch (NoSuchBeanDefinitionException ex) {
BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
if (parentBeanFactory instanceof ConfigurableListableBeanFactory) {
return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory);
if (parentBeanFactory instanceof ConfigurableListableBeanFactory configurableListableBeanFactory) {
return getBeanDefinition(beanName, configurableListableBeanFactory);
}
throw ex;
}

@ -940,8 +940,8 @@ class CacheAutoConfigurationTests extends AbstractCacheAutoConfigurationTests {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof CacheManager) {
this.cacheManagers.add((CacheManager) bean);
if (bean instanceof CacheManager cacheManager) {
this.cacheManagers.add(cacheManager);
return new SimpleCacheManager();
}
return bean;

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -246,8 +246,8 @@ class RedisAutoConfigurationJedisTests {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof JedisConnectionFactory) {
connectionFactory = (JedisConnectionFactory) bean;
if (bean instanceof JedisConnectionFactory jedisConnectionFactory) {
connectionFactory = jedisConnectionFactory;
}
return bean;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -161,8 +161,8 @@ class HttpMessageConvertersTests {
private AllEncompassingFormHttpMessageConverter findFormConverter(Collection<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof AllEncompassingFormHttpMessageConverter) {
return (AllEncompassingFormHttpMessageConverter) converter;
if (converter instanceof AllEncompassingFormHttpMessageConverter allEncompassingConverter) {
return allEncompassingConverter;
}
}
return null;

@ -376,8 +376,8 @@ class ArtemisAutoConfigurationTests {
assertThat(transportConfig.getFactoryClassName()).isEqualTo(NettyConnectorFactory.class.getName());
assertThat(transportConfig.getParams().get("host")).isEqualTo(host);
Object transportConfigPort = transportConfig.getParams().get("port");
if (transportConfigPort instanceof String) {
transportConfigPort = Integer.parseInt((String) transportConfigPort);
if (transportConfigPort instanceof String portString) {
transportConfigPort = Integer.parseInt(portString);
}
assertThat(transportConfigPort).isEqualTo(port);
return transportConfig;

@ -364,8 +364,7 @@ class TomcatWebServerFactoryCustomizerTests {
Valve[] valves = server.getTomcat().getHost().getPipeline().getValves();
assertThat(valves).hasAtLeastOneElementOfType(ErrorReportValve.class);
for (Valve valve : valves) {
if (valve instanceof ErrorReportValve) {
ErrorReportValve errorReportValve = (ErrorReportValve) valve;
if (valve instanceof ErrorReportValve errorReportValve) {
assertThat(errorReportValve.isShowReport()).isFalse();
assertThat(errorReportValve.isShowServerInfo()).isFalse();
}

@ -249,9 +249,9 @@ class UndertowWebServerFactoryCustomizerTests {
ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.class);
willAnswer((invocation) -> {
Object argument = invocation.getArgument(0);
Arrays.stream((argument instanceof UndertowBuilderCustomizer)
? new UndertowBuilderCustomizer[] { (UndertowBuilderCustomizer) argument }
: (UndertowBuilderCustomizer[]) argument).forEach((customizer) -> customizer.customize(builder));
Arrays.stream((argument instanceof UndertowBuilderCustomizer undertowCustomizer)
? new UndertowBuilderCustomizer[] { undertowCustomizer } : (UndertowBuilderCustomizer[]) argument)
.forEach((customizer) -> customizer.customize(builder));
return null;
}).given(factory).addBuilderCustomizers(any());
return factory;

@ -427,8 +427,8 @@ class WebFluxAutoConfigurationTests {
Map<PathPattern, Object> handlerMap = getHandlerMap(context);
assertThat(handlerMap).hasSize(2);
for (Object handler : handlerMap.values()) {
if (handler instanceof ResourceWebHandler) {
assertThat(((ResourceWebHandler) handler).getCacheControl()).usingRecursiveComparison()
if (handler instanceof ResourceWebHandler resourceWebHandler) {
assertThat(resourceWebHandler.getCacheControl()).usingRecursiveComparison()
.isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS));
}
}
@ -444,8 +444,8 @@ class WebFluxAutoConfigurationTests {
Map<PathPattern, Object> handlerMap = getHandlerMap(context);
assertThat(handlerMap).hasSize(2);
for (Object handler : handlerMap.values()) {
if (handler instanceof ResourceWebHandler) {
assertThat(((ResourceWebHandler) handler).getCacheControl()).usingRecursiveComparison()
if (handler instanceof ResourceWebHandler resourceWebHandler) {
assertThat(resourceWebHandler.getCacheControl()).usingRecursiveComparison()
.isEqualTo(CacheControl.maxAge(5, TimeUnit.SECONDS).proxyRevalidate());
}
}
@ -459,8 +459,8 @@ class WebFluxAutoConfigurationTests {
Map<PathPattern, Object> handlerMap = getHandlerMap(context);
assertThat(handlerMap).hasSize(2);
for (Object handler : handlerMap.values()) {
if (handler instanceof ResourceWebHandler) {
assertThat(((ResourceWebHandler) handler).isUseLastModified()).isFalse();
if (handler instanceof ResourceWebHandler resourceWebHandler) {
assertThat(resourceWebHandler.isUseLastModified()).isFalse();
}
}
});
@ -635,8 +635,8 @@ class WebFluxAutoConfigurationTests {
private Map<PathPattern, Object> getHandlerMap(ApplicationContext context) {
HandlerMapping mapping = context.getBean("resourceHandlerMapping", HandlerMapping.class);
if (mapping instanceof SimpleUrlHandlerMapping) {
return ((SimpleUrlHandlerMapping) mapping).getHandlerMap();
if (mapping instanceof SimpleUrlHandlerMapping simpleMapping) {
return simpleMapping.getHandlerMap();
}
return Collections.emptyMap();
}

@ -1021,16 +1021,16 @@ class WebMvcAutoConfigurationTests {
Map<String, Object> handlerMap = getHandlerMap(context.getBean("resourceHandlerMapping", HandlerMapping.class));
assertThat(handlerMap).hasSize(2);
for (Object handler : handlerMap.values()) {
if (handler instanceof ResourceHttpRequestHandler) {
handlerConsumer.accept((ResourceHttpRequestHandler) handler);
if (handler instanceof ResourceHttpRequestHandler resourceHandler) {
handlerConsumer.accept(resourceHandler);
}
}
}
protected Map<String, List<Resource>> getResourceMappingLocations(ApplicationContext context) {
Object bean = context.getBean("resourceHandlerMapping");
if (bean instanceof HandlerMapping) {
return getMappingLocations(context, (HandlerMapping) bean);
if (bean instanceof HandlerMapping handlerMapping) {
return getMappingLocations(context, handlerMapping);
}
assertThat(bean.toString()).isEqualTo("null");
return Collections.emptyMap();
@ -1066,8 +1066,8 @@ class WebMvcAutoConfigurationTests {
}
protected Map<String, Object> getHandlerMap(HandlerMapping mapping) {
if (mapping instanceof SimpleUrlHandlerMapping) {
return ((SimpleUrlHandlerMapping) mapping).getHandlerMap();
if (mapping instanceof SimpleUrlHandlerMapping handlerMapping) {
return handlerMapping.getHandlerMap();
}
return Collections.emptyMap();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -239,8 +239,8 @@ public class CommandRunner implements Iterable<Command> {
private int handleError(boolean debug, Exception ex) {
Set<CommandException.Option> options = NO_EXCEPTION_OPTIONS;
if (ex instanceof CommandException) {
options = ((CommandException) ex).getOptions();
if (ex instanceof CommandException commandException) {
options = commandException.getOptions();
if (options.contains(CommandException.Option.RETHROW)) {
throw (CommandException) ex;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 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.
@ -281,8 +281,8 @@ abstract class ArchiveCommand extends OptionParsingCommand {
@Override
public void visit(ASTNode[] nodes, SourceUnit source) {
for (ASTNode node : nodes) {
if (node instanceof ModuleNode) {
visitModule((ModuleNode) node);
if (node instanceof ModuleNode moduleNode) {
visitModule(moduleNode);
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2022 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.
@ -163,8 +163,7 @@ class InitializrServiceMetadata {
while (keys.hasNext()) {
String key = (String) keys.next();
Object o = root.get(key);
if (o instanceof JSONObject) {
JSONObject child = (JSONObject) o;
if (o instanceof JSONObject child) {
if (child.has(DEFAULT_ATTRIBUTE)) {
result.put(key, child.getString(DEFAULT_ATTRIBUTE));
}
@ -212,8 +211,8 @@ class InitializrServiceMetadata {
for (Iterator<?> iterator = json.keys(); iterator.hasNext();) {
String key = (String) iterator.next();
Object value = json.get(key);
if (value instanceof String) {
result.put(key, (String) value);
if (value instanceof String string) {
result.put(key, string);
}
}
return result;

@ -56,8 +56,8 @@ class ServiceCapabilitiesReportGenerator {
*/
String generate(String url) throws IOException {
Object content = this.initializrService.loadServiceCapabilities(url);
if (content instanceof InitializrServiceMetadata) {
return generateHelp(url, (InitializrServiceMetadata) content);
if (content instanceof InitializrServiceMetadata metadata) {
return generateHelp(url, metadata);
}
return content.toString();
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2021 the original author or authors.
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -76,8 +76,7 @@ public class SourceOptions {
List<String> sources = new ArrayList<>();
int sourceArgCount = 0;
for (Object option : nonOptionArguments) {
if (option instanceof String) {
String filename = (String) option;
if (option instanceof String filename) {
if ("--".equals(filename)) {
break;
}

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2022 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.
@ -221,8 +221,8 @@ public class Shell {
boolean handleSigInt() {
Command command = this.lastCommand;
if (command instanceof RunProcessCommand) {
return ((RunProcessCommand) command).handleSigInt();
if (command instanceof RunProcessCommand runProcessCommand) {
return runProcessCommand.handleSigInt();
}
return false;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save