From 5db04da2756b3c3bbba5434acc8c0805e9c4e6aa Mon Sep 17 00:00:00 2001 From: dreis2211 Date: Mon, 20 Jun 2022 18:14:16 +0200 Subject: [PATCH] Use pattern matching for instanceof where appropriate See gh-31475 --- .../boot/build/AsciidoctorConventions.java | 6 +-- .../boot/build/bom/BomExtension.java | 5 +-- .../boot/build/bom/BomPlugin.java | 10 ++--- .../bomr/github/StandardGitHubRepository.java | 4 +- .../version/AbstractDependencyVersion.java | 6 +-- .../ArtifactVersionDependencyVersion.java | 6 +-- .../ReleaseTrainDependencyVersion.java | 11 ++--- ...heckClasspathForUnnecessaryExclusions.java | 6 +-- .../build/mavenplugin/MavenPluginPlugin.java | 4 +- .../CloudFoundrySecurityInterceptor.java | 5 +-- ...CloudFoundryActuatorAutoConfiguration.java | 4 +- .../ReactiveCloudFoundrySecurityService.java | 4 +- .../CloudFoundrySecurityInterceptor.java | 3 +- ...SkipSslVerificationHttpRequestFactory.java | 6 +-- .../condition/ConditionsReportEndpoint.java | 6 +-- .../AutoConfiguredHealthEndpointGroups.java | 6 +-- .../health/HealthEndpointConfiguration.java | 12 +++--- ...rceHealthContributorAutoConfiguration.java | 3 +- .../LiquibaseEndpointAutoConfiguration.java | 4 +- .../metrics/MeterRegistryPostProcessor.java | 6 +-- .../autoconfigure/metrics/MeterValue.java | 14 +++---- ...ConnectionFactoryMetricsPostProcessor.java | 6 +-- ...onnectionPoolMetricsAutoConfiguration.java | 4 +- .../TaskExecutorMetricsAutoConfiguration.java | 8 ++-- .../ObservationRegistryPostProcessor.java | 4 +- .../security/reactive/EndpointRequest.java | 10 ++--- .../security/servlet/EndpointRequest.java | 10 ++--- .../ChildManagementContextInitializer.java | 8 ++-- .../ManagementContextAutoConfiguration.java | 4 +- ...etManagementChildContextConfiguration.java | 12 +++--- ...urcePoolMetricsAutoConfigurationTests.java | 4 +- .../boot/actuate/beans/BeansEndpoint.java | 6 +-- .../actuate/context/ShutdownEndpoint.java | 6 +-- ...ConfigurationPropertiesReportEndpoint.java | 4 +- .../endpoint/web/EndpointLinksResolver.java | 10 ++--- .../endpoint/web/PathMappedEndpoints.java | 6 +-- .../boot/actuate/env/EnvironmentEndpoint.java | 8 ++-- .../health/AbstractHealthIndicator.java | 10 ++--- .../boot/actuate/health/Health.java | 5 +-- .../health/ReactiveHealthContributor.java | 10 ++--- .../boot/actuate/health/Status.java | 6 +-- .../boot/actuate/info/Info.java | 5 +-- .../boot/actuate/metrics/MetricsEndpoint.java | 8 ++-- .../metrics/cache/CacheMetricsRegistrar.java | 6 +-- .../PrometheusPushGatewayManager.java | 4 +- .../startup/StartupTimeMetricsListener.java | 8 ++-- .../MetricsClientHttpRequestInterceptor.java | 6 +-- .../web/jetty/AbstractJettyMetricsBinder.java | 10 ++--- .../web/reactive/server/MetricsWebFilter.java | 5 +-- .../LongTaskTimingHandlerInterceptor.java | 6 +-- .../web/servlet/WebMvcMetricsFilter.java | 3 +- .../web/tomcat/TomcatMetricsBinder.java | 12 +++--- .../actuate/redis/RedisHealthIndicator.java | 4 +- .../redis/RedisReactiveHealthIndicator.java | 7 ++-- .../scheduling/ScheduledTasksEndpoint.java | 13 +++--- .../security/AuthenticationAuditListener.java | 10 ++--- .../security/AuthorizationAuditListener.java | 10 ++--- .../DispatcherServletHandlerMappings.java | 15 ++++--- ...herServletsMappingDescriptionProvider.java | 6 +-- .../FiltersMappingDescriptionProvider.java | 10 ++--- .../ServletsMappingDescriptionProvider.java | 10 ++--- ...EndpointTestInvocationContextProvider.java | 6 +-- ...ractDependsOnBeanFactoryPostProcessor.java | 6 +-- .../AutoConfigurationImportSelector.java | 16 +++---- ...tadataReaderFactoryContextInitializer.java | 10 ++--- .../aop/AopAutoConfiguration.java | 3 +- .../autoconfigure/cache/CacheCondition.java | 6 +-- .../condition/AbstractNestedCondition.java | 11 ++--- ...ReportAutoConfigurationImportListener.java | 6 +-- .../condition/ConditionMessage.java | 10 ++--- .../condition/OnBeanCondition.java | 29 +++++++------ .../condition/OnWarDeploymentCondition.java | 5 +-- .../condition/SpringBootCondition.java | 16 ++++--- .../NoSuchBeanDefinitionFailureAnalyzer.java | 4 +- .../http/HttpMessageConverters.java | 6 +-- .../EmbeddedLdapAutoConfiguration.java | 5 +-- ...ditionEvaluationReportLoggingListener.java | 9 ++-- .../PrimaryDefaultValidatorPostProcessor.java | 6 +-- .../validation/ValidatorAdapter.java | 31 +++++++------- .../JettyWebServerFactoryCustomizer.java | 18 ++++---- .../TomcatWebServerFactoryCustomizer.java | 4 +- .../ReactiveMultipartAutoConfiguration.java | 3 +- ...tiveWebServerFactoryAutoConfiguration.java | 4 +- ...vletWebServerFactoryAutoConfiguration.java | 4 +- .../web/servlet/WebMvcAutoConfiguration.java | 8 ++-- ...ependsOnBeanFactoryPostProcessorTests.java | 6 +-- .../cache/CacheAutoConfigurationTests.java | 4 +- .../RedisAutoConfigurationJedisTests.java | 6 +-- .../http/HttpMessageConvertersTests.java | 6 +-- .../ArtemisAutoConfigurationTests.java | 4 +- ...TomcatWebServerFactoryCustomizerTests.java | 3 +- ...dertowWebServerFactoryCustomizerTests.java | 6 +-- .../WebFluxAutoConfigurationTests.java | 16 +++---- .../servlet/WebMvcAutoConfigurationTests.java | 12 +++--- .../boot/cli/command/CommandRunner.java | 6 +-- .../cli/command/archive/ArchiveCommand.java | 6 +-- .../init/InitializrServiceMetadata.java | 9 ++-- .../ServiceCapabilitiesReportGenerator.java | 4 +- .../cli/command/options/SourceOptions.java | 5 +-- .../boot/cli/command/shell/Shell.java | 6 +-- .../AnnotatedNodeASTTransformation.java | 5 +-- .../boot/cli/compiler/AstUtils.java | 12 +++--- ...ndencyAutoConfigurationTransformation.java | 6 +-- ...DependencyManagementBomTransformation.java | 22 +++++----- .../compiler/ExtendedGroovyClassLoader.java | 6 +-- .../compiler/GenericBomAstTransformation.java | 22 +++++----- .../compiler/GroovyBeansTransformation.java | 5 +-- .../boot/cli/compiler/GroovyCompiler.java | 4 +- ...veDependencyCoordinatesTransformation.java | 8 ++-- .../springframework/boot/cli/CliTester.java | 6 +-- .../GenericBomAstTransformationTests.java | 6 +-- ...endencyCoordinatesTransformationTests.java | 6 +-- .../boot/devtools/filewatch/ChangedFile.java | 5 +-- .../boot/devtools/filewatch/ChangedFiles.java | 5 +-- .../devtools/filewatch/DirectorySnapshot.java | 6 +-- .../boot/devtools/filewatch/FileSnapshot.java | 5 +-- .../devtools/logger/DevToolsLogFactory.java | 6 +-- .../boot/devtools/restart/ChangeableUrls.java | 6 +-- .../restart/RestartApplicationListener.java | 14 +++---- .../boot/devtools/restart/Restarter.java | 4 +- .../restart/SilentExitExceptionHandler.java | 6 +-- .../restart/server/RestartServer.java | 6 +-- .../test/MockClientHttpRequestFactory.java | 6 +-- .../migrator/PropertiesMigrationListener.java | 6 +-- .../migrator/PropertyMigration.java | 5 +-- ...endencyInjectionTestExecutionListener.java | 7 ++-- .../jdbc/TestDatabaseAutoConfiguration.java | 5 +-- .../properties/AnnotationsPropertySource.java | 5 +-- .../web/servlet/WebDriverScope.java | 10 ++--- .../context/ImportsContextCustomizer.java | 14 +++---- .../test/context/SpringBootContextLoader.java | 4 +- .../boot/test/context/SpringBootTestArgs.java | 6 +-- .../assertj/ApplicationContextAssert.java | 6 +-- ...erApplicationContextInvocationHandler.java | 10 ++--- .../AbstractApplicationContextRunner.java | 9 ++-- .../boot/test/json/JsonContentAssert.java | 42 +++++++++---------- .../test/mock/mockito/DefinitionsParser.java | 8 ++-- .../boot/test/mock/mockito/MockReset.java | 6 +-- .../mockito/MockitoContextCustomizer.java | 6 +-- .../mock/mockito/MockitoPostProcessor.java | 8 ++-- .../mockito/MockitoTestExecutionListener.java | 6 +-- .../mock/mockito/QualifierDefinition.java | 5 +-- .../ResetMocksTestExecutionListener.java | 6 +-- .../boot/test/system/OutputCapture.java | 6 +-- .../util/ApplicationContextTestUtils.java | 6 +-- ...estRandomPortEnvironmentPostProcessor.java | 6 +-- .../RootUriRequestExpectationManager.java | 13 +++--- .../test/web/client/TestRestTemplate.java | 10 ++--- .../TestRestTemplateContextCustomizer.java | 6 +-- .../WebTestClientContextCustomizer.java | 6 +-- ...ltTestExecutionListenersPostProcessor.java | 5 +-- .../mockito/MockBeanContextCachingTests.java | 6 +-- .../AutoConfigureAnnotationProcessor.java | 4 +- .../boot/autoconfigureprocessor/Elements.java | 13 +++--- .../platform/docker/type/Binding.java | 5 +-- .../platform/io/InspectedContent.java | 8 ++-- .../configurationmetadata/JsonReader.java | 13 +++--- ...figurationMetadataAnnotationProcessor.java | 16 +++---- .../configurationprocessor/TypeUtils.java | 24 +++++------ .../metadata/JsonMarshaller.java | 13 +++--- .../AbstractFieldValuesProcessorTests.java | 6 +-- .../boot/gradle/plugin/JavaPluginAction.java | 3 +- .../boot/gradle/util/VersionExtractor.java | 6 +-- .../boot/jarmode/layertools/Context.java | 6 +-- .../loader/tools/DefaultLaunchScript.java | 6 +-- .../boot/loader/tools/JarWriter.java | 6 +-- .../boot/loader/tools/Packager.java | 12 +++--- .../tools/SizeCalculatingEntryWriter.java | 14 +++---- .../boot/loader/LaunchedURLClassLoader.java | 6 +-- .../boot/loader/PropertiesLauncher.java | 13 +++--- .../boot/loader/jar/Handler.java | 10 ++--- .../boot/loader/jar/JarFile.java | 4 +- .../boot/loader/jar/JarFileEntries.java | 2 +- .../boot/loader/jar/JarFileWrapper.java | 8 ++-- .../boot/loader/jar/StringSequence.java | 5 +-- .../boot/maven/CustomLayersProvider.java | 4 +- .../JavaCompilerPluginConfiguration.java | 5 +-- .../boot/maven/VersionExtractor.java | 6 +-- .../ModifiedClassPathClassLoader.java | 4 +- .../testsupport/system/OutputCapture.java | 6 +-- .../boot/BeanDefinitionLoader.java | 24 +++++------ ...nitializationBeanFactoryPostProcessor.java | 6 +-- .../boot/SpringApplication.java | 40 +++++++++--------- ...SpringApplicationAdminMXBeanRegistrar.java | 10 ++--- ...arentContextCloserApplicationListener.java | 8 ++-- .../boot/cloud/CloudPlatform.java | 6 +-- .../context/ApplicationPidFileWriter.java | 14 +++---- ...WarningsApplicationContextInitializer.java | 5 +-- .../context/config/ConfigDataEnvironment.java | 8 ++-- ...onmentContributorPlaceholdersResolver.java | 4 +- .../context/config/ConfigDataImporter.java | 6 +-- .../config/ConfigDataLocationBindHandler.java | 14 +++---- .../config/ConfigDataLocationResolvers.java | 4 +- .../ConfigDataNotFoundFailureAnalyzer.java | 10 ++--- .../config/DelegatingApplicationListener.java | 7 ++-- .../StandardConfigDataLocationResolver.java | 4 +- .../event/EventPublishingRunListener.java | 11 +++-- .../logging/LoggingApplicationListener.java | 16 +++---- .../ConfigurationPropertiesBean.java | 12 +++--- .../ConfigurationPropertiesBeanRegistrar.java | 6 +-- .../ConfigurationPropertiesBinder.java | 10 ++--- .../properties/ConversionServiceDeducer.java | 6 +-- .../properties/PropertySourcesDeducer.java | 6 +-- .../boot/context/properties/bind/Binder.java | 4 +- .../bind/IndexedElementsBinder.java | 6 +-- .../context/properties/bind/MapBinder.java | 4 +- .../PropertySourcesPlaceholdersResolver.java | 6 +-- .../properties/bind/ValueObjectBinder.java | 6 +-- .../bind/validation/ValidationErrors.java | 6 +-- .../CachingConfigurationPropertySource.java | 6 +-- .../source/ConfigurationPropertySources.java | 4 +- ...rationPropertySourcesPropertyResolver.java | 10 ++--- .../SpringConfigurationPropertySource.java | 7 ++-- .../SpringConfigurationPropertySources.java | 6 +-- ...ngIterableConfigurationPropertySource.java | 6 +-- .../convert/ApplicationConversionService.java | 6 +-- .../CharSequenceToObjectConverter.java | 5 +-- ...InputStreamSourceToByteArrayConverter.java | 6 +-- .../boot/diagnostics/FailureAnalyzers.java | 8 ++-- ...eanCurrentlyInCreationFailureAnalyzer.java | 14 +++---- .../BindValidationFailureAnalyzer.java | 6 +-- ...nmentPostProcessorApplicationListener.java | 4 +- .../env/OriginTrackedMapPropertySource.java | 10 ++--- .../boot/env/OriginTrackedYamlLoader.java | 10 ++--- .../boot/jackson/JsonComponentModule.java | 10 ++--- .../boot/jackson/JsonObjectDeserializer.java | 6 +-- .../boot/jackson/JsonObjectSerializer.java | 6 +-- .../boot/jdbc/DataSourceUnwrapper.java | 10 ++--- .../boot/logging/DeferredLog.java | 6 +-- .../boot/logging/LoggerConfiguration.java | 5 +-- .../boot/logging/LoggingSystemProperties.java | 6 +-- .../logging/log4j2/Log4J2LoggingSystem.java | 4 +- .../logging/logback/LogbackConfigurator.java | 6 +-- .../LogbackLoggingSystemProperties.java | 4 +- .../springframework/boot/origin/Origin.java | 14 +++---- .../boot/origin/OriginTrackedResource.java | 4 +- .../boot/origin/OriginTrackedValue.java | 6 +-- .../boot/origin/TextResourceOrigin.java | 13 +++--- .../boot/r2dbc/ConnectionFactoryBuilder.java | 4 +- ...PortInfoApplicationContextInitializer.java | 6 +-- ...aseInitializationDependencyConfigurer.java | 4 +- .../boot/system/ApplicationHome.java | 6 +-- .../boot/system/ApplicationPid.java | 4 +- .../boot/system/ApplicationTemp.java | 6 +-- ...PortInfoApplicationContextInitializer.java | 6 +-- .../context/WebServerApplicationContext.java | 10 ++--- .../web/context/WebServerPortFileWriter.java | 6 +-- .../jetty/JettyServletWebServerFactory.java | 3 +- .../web/embedded/jetty/JettyWebServer.java | 39 +++++++++-------- .../web/embedded/netty/NettyWebServer.java | 6 +-- ...bleReferenceClearingContextCustomizer.java | 5 +-- .../tomcat/TomcatServletWebServerFactory.java | 7 ++-- .../web/embedded/tomcat/TomcatWebServer.java | 18 ++++---- .../undertow/UndertowServletWebServer.java | 6 +-- .../UndertowServletWebServerFactory.java | 4 +- .../embedded/undertow/UndertowWebServer.java | 12 +++--- .../error/DefaultErrorAttributes.java | 11 +++-- .../boot/web/server/ErrorPage.java | 5 +-- .../ErrorPageRegistrarBeanPostProcessor.java | 6 +-- .../boot/web/server/MimeMappings.java | 6 +-- ...verFactoryCustomizerBeanPostProcessor.java | 6 +-- ...vletComponentRegisteringPostProcessor.java | 7 ++-- .../ServletContextInitializerBeans.java | 3 +- .../servlet/error/DefaultErrorAttributes.java | 6 +-- .../boot/web/servlet/server/DocumentRoot.java | 6 +-- .../servlet/server/StaticResourceJars.java | 6 +-- .../web/servlet/support/ErrorPageFilter.java | 20 ++++----- .../support/SpringBootServletInitializer.java | 8 ++-- .../SpringApplicationBuilderTests.java | 4 +- ...nfigDataEnvironmentPostProcessorTests.java | 4 +- .../convert/ConversionServiceArguments.java | 6 +-- .../boot/jackson/NameAndAge.java | 5 +-- .../boot/jdbc/DataSourceBuilderTests.java | 6 +-- .../JettyServletWebServerFactoryTests.java | 8 ++-- .../TomcatServletWebServerFactoryTests.java | 12 +++--- ...ctiveWebServerApplicationContextTests.java | 6 +-- ...AbstractReactiveWebServerFactoryTests.java | 3 +- ...rvletWebServerApplicationContextTests.java | 4 +- 278 files changed, 1049 insertions(+), 1126 deletions(-) diff --git a/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java b/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java index cccc9243f8..1b2123e4e7 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/AsciidoctorConventions.java @@ -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)); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java index b35cbd78fc..d843873796 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java @@ -300,7 +300,7 @@ public class BomExtension { public void setModules(List 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); diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java index 2fc264df80..2f273b219c 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/BomPlugin.java @@ -255,9 +255,8 @@ public class BomPlugin implements Plugin { 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 { } 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())) { diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHubRepository.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHubRepository.java index 2c9059f3ec..73aa7435b0 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHubRepository.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/github/StandardGitHubRepository.java @@ -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; } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/AbstractDependencyVersion.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/AbstractDependencyVersion.java index 0192c64f6f..1a0ef1ce97 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/AbstractDependencyVersion.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/AbstractDependencyVersion.java @@ -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); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ArtifactVersionDependencyVersion.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ArtifactVersionDependencyVersion.java index 4c2b9df6d3..296cf41ef3 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ArtifactVersionDependencyVersion.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ArtifactVersionDependencyVersion.java @@ -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 extractArtifactVersionDependencyVersion( DependencyVersion other) { ArtifactVersionDependencyVersion artifactVersion = null; - if (other instanceof ArtifactVersionDependencyVersion) { - artifactVersion = (ArtifactVersionDependencyVersion) other; + if (other instanceof ArtifactVersionDependencyVersion otherVersion) { + artifactVersion = otherVersion; } return Optional.ofNullable(artifactVersion); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ReleaseTrainDependencyVersion.java b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ReleaseTrainDependencyVersion.java index 0fbb7703ba..838ba33e8b 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ReleaseTrainDependencyVersion.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/version/ReleaseTrainDependencyVersion.java @@ -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); } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java index 797f2df3fb..e2ecbf1765 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnnecessaryExclusions.java @@ -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); } } diff --git a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java index 9bb0bb1977..fd5eb5467e 100644 --- a/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java +++ b/buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java @@ -373,9 +373,7 @@ public class MavenPluginPlugin implements Plugin { @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('.', '/') + "/" diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java index 096313574e..dd209ff8be 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/CloudFoundrySecurityInterceptor.java @@ -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 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() + "\"}")); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java index bc3419eae2..6e92fc85cd 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfiguration.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java index 55d2cfd562..8b9ecef470 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundrySecurityService.java @@ -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"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java index 5bb653d4c9..01eafcf651 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityInterceptor.java @@ -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() + "\"}"); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java index c613c16a2e..54a9e10dba 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactory.java @@ -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); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java index f05873f64e..2d232340c8 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroups.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroups.java index 58a1f0e3f6..55be3d1a22 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroups.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/AutoConfiguredHealthEndpointGroups.java @@ -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 roles = properties.getRoles(); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.java index a63d67739e..01159b37da 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.java @@ -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()); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java index 8a55cc053a..b07d4d4e05 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.java @@ -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)); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java index 266145b239..c2acc67446 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/liquibase/LiquibaseEndpointAutoConfiguration.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java index 76561d9b51..860dceac86 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValue.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValue.java index d01b188cde..d475f8c5d6 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValue.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/MeterValue.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java index 075ccfdd6e..de1835d8ee 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/amqp/RabbitConnectionFactoryMetricsPostProcessor.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfiguration.java index dd6775a9a2..6da2a37f51 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/r2dbc/ConnectionPoolMetricsAutoConfiguration.java @@ -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()); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfiguration.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfiguration.java index e530be89bc..8f6dcfdaf9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfiguration.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/metrics/task/TaskExecutorMetricsAutoConfiguration.java @@ -54,11 +54,11 @@ public class TaskExecutorMetricsAutoConfiguration { @Autowired public void bindTaskExecutorsToRegistry(Map 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); } }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryPostProcessor.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryPostProcessor.java index 3ea73d2deb..24e4814a12 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryPostProcessor.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/observation/ObservationRegistryPostProcessor.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java index 0097d5299a..7b8cbc0e7d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/reactive/EndpointRequest.java @@ -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); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java index 03ed9ef8bc..1b9d73701e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/security/servlet/EndpointRequest.java @@ -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); diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java index 9e4335e224..054109f391 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java @@ -205,11 +205,11 @@ class ChildManagementContextInitializer implements ApplicationListener 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); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java index 7da9f12146..26e8a10476 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpoints.java @@ -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 { private Map getEndpoints(Collection> suppliers) { Map 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); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java index 04c9928fd6..28fa44c22b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/env/EnvironmentEndpoint.java @@ -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> 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); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java index 0e9bcabfc0..ebf13309c9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/AbstractHealthIndicator.java @@ -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); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java index d0f293e28d..06339e19c2 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Health.java @@ -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; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributor.java index 89b4c3a148..0519c5c268 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/ReactiveHealthContributor.java @@ -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"); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java index 1ee5f47051..d4113e57a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java @@ -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; } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java index ef7cf60eb7..452d3c34c9 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/info/Info.java @@ -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; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java index 785b8d8c26..549d961e57 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/MetricsEndpoint.java @@ -64,8 +64,8 @@ public class MetricsEndpoint { } private void collectNames(Set 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 findFirstMatchingMeters(MeterRegistry registry, String name, Iterable 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(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java index 61cbd08e11..b5dea5a746 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/cache/CacheMetricsRegistrar.java @@ -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) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java index 504f066f62..6d150d44a4 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/export/prometheus/PrometheusPushGatewayManager.java @@ -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) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java index 3c6cc84cb4..12e900763a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/startup/StartupTimeMetricsListener.java @@ -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); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java index 8da5d69a48..ac1ba1b3e0 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/client/MetricsClientHttpRequestInterceptor.java @@ -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); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/AbstractJettyMetricsBinder.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/AbstractJettyMetricsBinder.java index 93b8b41fb5..0d26c1816e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/AbstractJettyMetricsBinder.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/jetty/AbstractJettyMetricsBinder.java @@ -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; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java index 357ca2f760..0eeffcf77f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/reactive/server/MetricsWebFilter.java @@ -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 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(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java index b92c7b6e6c..38e53a927a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/LongTaskTimingHandlerInterceptor.java @@ -109,10 +109,10 @@ public class LongTaskTimingHandlerInterceptor implements HandlerInterceptor { } private Set 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 getTimedAnnotations(HandlerMethod handler) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java index 7cbd7c8183..e2dac785b8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/servlet/WebMvcMetricsFilter.java @@ -147,8 +147,7 @@ public class WebMvcMetricsFilter extends OncePerRequestFilter { } private Set 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(); diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java index 45ad5a4acf..fb58802647 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/metrics/web/tomcat/TomcatMetricsBinder.java @@ -65,10 +65,10 @@ public class TomcatMetricsBinder implements ApplicationListener 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)); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java index 1063877cfb..8b408145f2 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/scheduling/ScheduledTasksEndpoint.java @@ -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 { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java index bb4a3e96ab..fed98e54f8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthenticationAuditListener.java @@ -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); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java index c7b11918a1..f151a4e52a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java @@ -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); } } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java index 78a295851b..148676e92a 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletHandlerMappings.java @@ -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) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java index d93826fbcf..49b7e2ba3e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/DispatcherServletsMappingDescriptionProvider.java @@ -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> describeMappings(ApplicationContext context) { - if (context instanceof WebApplicationContext) { - return describeMappings((WebApplicationContext) context); + if (context instanceof WebApplicationContext webApplicationContext) { + return describeMappings(webApplicationContext); } return Collections.emptyMap(); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java index e287ce9dcc..c091d2dcfa 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/FiltersMappingDescriptionProvider.java @@ -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,11 +38,11 @@ public class FiltersMappingDescriptionProvider implements MappingDescriptionProv @Override public List describeMappings(ApplicationContext context) { - if (!(context instanceof WebApplicationContext)) { - return Collections.emptyList(); + if (context instanceof WebApplicationContext webApplicationContext) { + return webApplicationContext.getServletContext().getFilterRegistrations().values().stream() + .map(FilterRegistrationMappingDescription::new).collect(Collectors.toList()); } - return ((WebApplicationContext) context).getServletContext().getFilterRegistrations().values().stream() - .map(FilterRegistrationMappingDescription::new).collect(Collectors.toList()); + return Collections.emptyList(); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java index 4734997ca4..8c36e61811 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/mappings/servlet/ServletsMappingDescriptionProvider.java @@ -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,11 +38,11 @@ public class ServletsMappingDescriptionProvider implements MappingDescriptionPro @Override public List describeMappings(ApplicationContext context) { - if (!(context instanceof WebApplicationContext)) { - return Collections.emptyList(); + if (context instanceof WebApplicationContext webApplicationContext) { + return webApplicationContext.getServletContext().getServletRegistrations().values().stream() + .map(ServletRegistrationMappingDescription::new).collect(Collectors.toList()); } - return ((WebApplicationContext) context).getServletContext().getServletRegistrations().values().stream() - .map(ServletRegistrationMappingDescription::new).collect(Collectors.toList()); + return Collections.emptyList(); } @Override diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java index 283d085aff..4d2ca1883a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/test/WebEndpointTestInvocationContextProvider.java @@ -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(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java index 8b7b44f15e..d78c8f2881 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessor.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java index 41569923e9..d7a6a72c4d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java @@ -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); } } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java index f382164764..f6dfdeb9e0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java index ecd13d6ff2..4767aac8b4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java @@ -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); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java index 806f272ab5..884bf693d6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache/CacheCondition.java @@ -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(); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java index 7b09eea45c..2b615cb74b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/AbstractNestedCondition.java @@ -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()); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java index 4d29ea9356..99611156dc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReportAutoConfigurationImportListener.java @@ -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; } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java index 42c9826464..31547d3866 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java @@ -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 diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java index ddc99827fe..ed9e7c47f4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java @@ -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 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); } } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java index b0a9c978f3..fb0e5388d2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnWarDeploymentCondition.java @@ -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."); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java index ad09dbc1cf..6db09ae38a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java @@ -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); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java index 728a0c91e8..50264211cb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java index 2ca518f800..e567392693 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/http/HttpMessageConverters.java @@ -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> } } combined.add(defaultConverter); - if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter) { - configurePartConverters((AllEncompassingFormHttpMessageConverter) defaultConverter, converters); + if (defaultConverter instanceof AllEncompassingFormHttpMessageConverter allEncompassingConverter) { + configurePartConverters(allEncompassingConverter, converters); } } combined.addAll(0, processing); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java index c521fd7bf5..a19538b6de 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ldap/embedded/EmbeddedLdapAutoConfiguration.java @@ -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) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java index b97fe44325..a81b68a4b2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java @@ -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); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java index db9eabcd29..d23d59cc1f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/PrimaryDefaultValidatorPostProcessor.java @@ -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; } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java index 8a3ecb95f1..84bd614b18 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java index d5d0f8d253..e6677bdcf0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/JettyWebServerFactoryCustomizer.java @@ -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()); } } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java index e53729ab1c..8bfb7b164a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizer.java @@ -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) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java index c38bb82209..93646b4802 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveMultipartAutoConfiguration.java @@ -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); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java index 8b560d7c99..f16b57e872 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/reactive/ReactiveWebServerFactoryAutoConfiguration.java @@ -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; } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java index 8546fae4c3..ea9a919c06 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryAutoConfiguration.java @@ -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; } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java index ae3871bbfd..d32bb2599d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java @@ -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()); } } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java index fe5df9e4da..faa312ddeb 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AbstractDependsOnBeanFactoryPostProcessorTests.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java index 5ceabc3410..2336521f42 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/cache/CacheAutoConfigurationTests.java @@ -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; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java index 4a834b40bb..bda55a3dcc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/data/redis/RedisAutoConfigurationJedisTests.java @@ -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; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java index 06a0184a6e..669e2c7e76 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/http/HttpMessageConvertersTests.java @@ -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> converters) { for (HttpMessageConverter converter : converters) { - if (converter instanceof AllEncompassingFormHttpMessageConverter) { - return (AllEncompassingFormHttpMessageConverter) converter; + if (converter instanceof AllEncompassingFormHttpMessageConverter allEncompassingConverter) { + return allEncompassingConverter; } } return null; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java index 87b0641cdf..207e243733 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jms/artemis/ArtemisAutoConfigurationTests.java @@ -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; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java index a12d66738b..aa5ffdfaf5 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/TomcatWebServerFactoryCustomizerTests.java @@ -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(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java index 7b544fb3e6..53fec27b8d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/embedded/UndertowWebServerFactoryCustomizerTests.java @@ -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; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java index 1cb5b3e79e..3b19c57177 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/WebFluxAutoConfigurationTests.java @@ -427,8 +427,8 @@ class WebFluxAutoConfigurationTests { Map 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 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 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 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(); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java index 8523a21020..11cd8492f0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java @@ -1021,16 +1021,16 @@ class WebMvcAutoConfigurationTests { Map 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> 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 getHandlerMap(HandlerMapping mapping) { - if (mapping instanceof SimpleUrlHandlerMapping) { - return ((SimpleUrlHandlerMapping) mapping).getHandlerMap(); + if (mapping instanceof SimpleUrlHandlerMapping handlerMapping) { + return handlerMapping.getHandlerMap(); } return Collections.emptyMap(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java index 1cb7439ec5..5a4723b1c7 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java @@ -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 { private int handleError(boolean debug, Exception ex) { Set 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; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java index d0732c163a..fb71db4c1a 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/archive/ArchiveCommand.java @@ -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); } } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java index cb593d912f..7bb121175c 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java @@ -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; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java index 352b050138..1e1492d046 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ServiceCapabilitiesReportGenerator.java @@ -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(); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java index 29b0e07bb2..cfca382498 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/SourceOptions.java @@ -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 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; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java index 917a4fa2f8..1354839756 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/Shell.java @@ -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; } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java index 97523c8370..b9f20a2e12 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AnnotatedNodeASTTransformation.java @@ -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. @@ -57,8 +57,7 @@ public abstract class AnnotatedNodeASTTransformation implements ASTTransformatio List annotationNodes = new ArrayList<>(); ClassVisitor classVisitor = new ClassVisitor(source, annotationNodes); for (ASTNode node : nodes) { - if (node instanceof ModuleNode) { - ModuleNode module = (ModuleNode) node; + if (node instanceof ModuleNode module) { visitAnnotatedNode(module.getPackage(), annotationNodes); for (ImportNode importNode : module.getImports()) { visitAnnotatedNode(importNode, annotationNodes); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java index 6b9e221957..f2a1dc34d1 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/AstUtils.java @@ -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. @@ -149,8 +149,8 @@ public abstract class AstUtils { public static ClosureExpression getClosure(BlockStatement block, String name, boolean remove) { for (ExpressionStatement statement : getExpressionStatements(block)) { Expression expression = statement.getExpression(); - if (expression instanceof MethodCallExpression) { - ClosureExpression closure = getClosure(name, (MethodCallExpression) expression); + if (expression instanceof MethodCallExpression methodCallExpression) { + ClosureExpression closure = getClosure(name, methodCallExpression); if (closure != null) { if (remove) { block.getStatements().remove(statement); @@ -165,8 +165,8 @@ public abstract class AstUtils { private static List getExpressionStatements(BlockStatement block) { List statements = new ArrayList<>(); for (Statement statement : block.getStatements()) { - if (statement instanceof ExpressionStatement) { - statements.add((ExpressionStatement) statement); + if (statement instanceof ExpressionStatement expressionStatement) { + statements.add(expressionStatement); } } return statements; @@ -174,7 +174,7 @@ public abstract class AstUtils { private static ClosureExpression getClosure(String name, MethodCallExpression expression) { Expression method = expression.getMethod(); - if (method instanceof ConstantExpression && name.equals(((ConstantExpression) method).getValue())) { + if (method instanceof ConstantExpression constantExpression && name.equals(constantExpression.getValue())) { return (ClosureExpression) ((ArgumentListExpression) expression.getArguments()).getExpression(0); } return null; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyAutoConfigurationTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyAutoConfigurationTransformation.java index 8f5af16661..c287652ebd 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyAutoConfigurationTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyAutoConfigurationTransformation.java @@ -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,8 +62,8 @@ public class DependencyAutoConfigurationTransformation implements ASTTransformat @Override public void visit(ASTNode[] nodes, SourceUnit source) { for (ASTNode astNode : nodes) { - if (astNode instanceof ModuleNode) { - visitModule((ModuleNode) astNode); + if (astNode instanceof ModuleNode moduleNode) { + visitModule(moduleNode); } } } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java index f613953666..43c7b56dda 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/DependencyManagementBomTransformation.java @@ -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. @@ -107,8 +107,8 @@ public class DependencyManagementBomTransformation extends AnnotatedNodeASTTrans List> dependencies = new ArrayList<>(constantExpressions.size()); for (ConstantExpression expression : constantExpressions) { Object value = expression.getValue(); - if (value instanceof String) { - String[] components = ((String) expression.getValue()).split(":"); + if (value instanceof String string) { + String[] components = string.split(":"); if (components.length == 3) { dependency = new HashMap<>(); dependency.put("group", components[0]); @@ -126,12 +126,12 @@ public class DependencyManagementBomTransformation extends AnnotatedNodeASTTrans } private List getConstantExpressions(Expression valueExpression) { - if (valueExpression instanceof ListExpression) { - return getConstantExpressions((ListExpression) valueExpression); + if (valueExpression instanceof ListExpression listExpression) { + return getConstantExpressions(listExpression); } - if (valueExpression instanceof ConstantExpression - && ((ConstantExpression) valueExpression).getValue() instanceof String) { - return Arrays.asList((ConstantExpression) valueExpression); + if (valueExpression instanceof ConstantExpression constantExpression + && constantExpression.getValue() instanceof String) { + return Arrays.asList(constantExpression); } reportError("@DependencyManagementBom requires an inline constant that is a string or a string array", valueExpression); @@ -141,9 +141,9 @@ public class DependencyManagementBomTransformation extends AnnotatedNodeASTTrans private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList<>(); for (Expression expression : valueExpression.getExpressions()) { - if (expression instanceof ConstantExpression - && ((ConstantExpression) expression).getValue() instanceof String) { - expressions.add((ConstantExpression) expression); + if (expression instanceof ConstantExpression constantExpression + && constantExpression.getValue() instanceof String) { + expressions.add(constantExpression); } else { reportError("Each entry in the array must be an inline string constant", expression); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java index b2ee934316..9325849d57 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoader.java @@ -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. @@ -188,8 +188,8 @@ public class ExtendedGroovyClassLoader extends GroovyClassLoader { private void findGroovyJarsDirectly(ClassLoader classLoader, Set urls) { while (classLoader != null) { - if (classLoader instanceof URLClassLoader) { - for (URL url : ((URLClassLoader) classLoader).getURLs()) { + if (classLoader instanceof URLClassLoader urlClassLoader) { + for (URL url : urlClassLoader.getURLs()) { if (isGroovyJar(url.toString())) { urls.add(url); } diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java index 1ef7e457f0..91b10e0a79 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GenericBomAstTransformation.java @@ -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. @@ -58,8 +58,8 @@ public abstract class GenericBomAstTransformation implements SpringBootAstTransf @Override public void visit(ASTNode[] nodes, SourceUnit source) { for (ASTNode astNode : nodes) { - if (astNode instanceof ModuleNode) { - visitModule((ModuleNode) astNode, getBomModule()); + if (astNode instanceof ModuleNode moduleNode) { + visitModule(moduleNode, getBomModule()); } } } @@ -107,12 +107,12 @@ public abstract class GenericBomAstTransformation implements SpringBootAstTransf } private List getConstantExpressions(Expression valueExpression) { - if (valueExpression instanceof ListExpression) { - return getConstantExpressions((ListExpression) valueExpression); + if (valueExpression instanceof ListExpression listExpression) { + return getConstantExpressions(listExpression); } - if (valueExpression instanceof ConstantExpression - && ((ConstantExpression) valueExpression).getValue() instanceof String) { - return Arrays.asList((ConstantExpression) valueExpression); + if (valueExpression instanceof ConstantExpression constantExpression + && constantExpression.getValue() instanceof String) { + return Arrays.asList(constantExpression); } return Collections.emptyList(); } @@ -120,9 +120,9 @@ public abstract class GenericBomAstTransformation implements SpringBootAstTransf private List getConstantExpressions(ListExpression valueExpression) { List expressions = new ArrayList<>(); for (Expression expression : valueExpression.getExpressions()) { - if (expression instanceof ConstantExpression - && ((ConstantExpression) expression).getValue() instanceof String) { - expressions.add((ConstantExpression) expression); + if (expression instanceof ConstantExpression constantExpression + && constantExpression.getValue() instanceof String) { + expressions.add(constantExpression); } } return expressions; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java index f286a27384..6d4cbaf1cd 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyBeansTransformation.java @@ -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. @@ -52,8 +52,7 @@ public class GroovyBeansTransformation implements ASTTransformation { @Override public void visit(ASTNode[] nodes, SourceUnit source) { for (ASTNode node : nodes) { - if (node instanceof ModuleNode) { - ModuleNode module = (ModuleNode) node; + if (node instanceof ModuleNode module) { for (ClassNode classNode : new ArrayList<>(module.getClasses())) { if (classNode.isScript()) { classNode.visitContents(new ClassVisitor(source, classNode)); diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java index 4a9602cf0c..24ef668e9b 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/GroovyCompiler.java @@ -153,8 +153,8 @@ public class GroovyCompiler { private URL[] getExistingUrls() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl instanceof ExtendedGroovyClassLoader) { - return ((ExtendedGroovyClassLoader) tccl).getURLs(); + if (tccl instanceof ExtendedGroovyClassLoader groovyClassLoader) { + return groovyClassLoader.getURLs(); } else { return new URL[0]; diff --git a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java index c37210d94f..fe2fc3f4a0 100644 --- a/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java +++ b/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformation.java @@ -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. @@ -73,9 +73,9 @@ public class ResolveDependencyCoordinatesTransformation extends AnnotatedNodeAST private String getValue(AnnotationNode annotation) { Expression expression = annotation.getMember("value"); - if (expression instanceof ConstantExpression) { - Object value = ((ConstantExpression) expression).getValue(); - return (value instanceof String) ? (String) value : null; + if (expression instanceof ConstantExpression constantExpression) { + Object value = constantExpression.getValue(); + return (value instanceof String string) ? string : null; } return null; } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java index 6e28f4dbc5..8840926355 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java @@ -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. @@ -184,8 +184,8 @@ public class CliTester implements BeforeEachCallback, AfterEachCallback { @Override public void afterEach(ExtensionContext extensionContext) { for (AbstractCommand command : this.commands) { - if (command != null && command instanceof RunCommand) { - ((RunCommand) command).stop(); + if (command instanceof RunCommand runCommand) { + runCommand.stop(); } } System.clearProperty("disableSpringSnapshotRepos"); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java index 7f80939c89..5b4d864cd6 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/GenericBomAstTransformationTests.java @@ -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,9 +91,9 @@ final class GenericBomAstTransformationTests { private List getValue() { Expression expression = findAnnotation().getMember("value"); - if (expression instanceof ListExpression) { + if (expression instanceof ListExpression listExpression) { List list = new ArrayList<>(); - for (Expression ex : ((ListExpression) expression).getExpressions()) { + for (Expression ex : listExpression.getExpressions()) { list.add((String) ((ConstantExpression) ex).getValue()); } return list; diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java index cbea73ba22..8a5d49f0ae 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ResolveDependencyCoordinatesTransformationTests.java @@ -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. @@ -225,8 +225,8 @@ final class ResolveDependencyCoordinatesTransformationTests { private Object getGrabAnnotationMemberAsString(String memberName) { Expression expression = this.grabAnnotation.getMember(memberName); - if (expression instanceof ConstantExpression) { - return ((ConstantExpression) expression).getValue(); + if (expression instanceof ConstantExpression constantExpression) { + return constantExpression.getValue(); } else if (expression == null) { return null; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java index c1e97b2178..f4cae7d659 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFile.java @@ -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. @@ -89,8 +89,7 @@ public final class ChangedFile { if (obj == null) { return false; } - if (obj instanceof ChangedFile) { - ChangedFile other = (ChangedFile) obj; + if (obj instanceof ChangedFile other) { return this.file.equals(other.file) && this.type.equals(other.type); } return super.equals(obj); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java index 7697d60d5b..d0375dd2c5 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/ChangedFiles.java @@ -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. @@ -69,8 +69,7 @@ public final class ChangedFiles implements Iterable { if (obj == this) { return true; } - if (obj instanceof ChangedFiles) { - ChangedFiles other = (ChangedFiles) obj; + if (obj instanceof ChangedFiles other) { return this.sourceDirectory.equals(other.sourceDirectory) && this.files.equals(other.files); } return super.equals(obj); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/DirectorySnapshot.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/DirectorySnapshot.java index f16156456a..040a69e02c 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/DirectorySnapshot.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/DirectorySnapshot.java @@ -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. @@ -119,8 +119,8 @@ class DirectorySnapshot { if (obj == null) { return false; } - if (obj instanceof DirectorySnapshot) { - return equals((DirectorySnapshot) obj, null); + if (obj instanceof DirectorySnapshot other) { + return equals(other, null); } return super.equals(obj); } diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSnapshot.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSnapshot.java index d50933a571..ef29927d11 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSnapshot.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/filewatch/FileSnapshot.java @@ -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. @@ -56,8 +56,7 @@ class FileSnapshot { if (obj == null) { return false; } - if (obj instanceof FileSnapshot) { - FileSnapshot other = (FileSnapshot) obj; + if (obj instanceof FileSnapshot other) { boolean equals = this.file.equals(other.file); equals = equals && this.exists == other.exists; equals = equals && this.length == other.length; diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/logger/DevToolsLogFactory.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/logger/DevToolsLogFactory.java index 1c81fc3283..fd1b5bc98a 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/logger/DevToolsLogFactory.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/logger/DevToolsLogFactory.java @@ -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. @@ -62,8 +62,8 @@ public final class DevToolsLogFactory { public void onApplicationEvent(ApplicationPreparedEvent event) { synchronized (logs) { logs.forEach((log, source) -> { - if (log instanceof DeferredLog) { - ((DeferredLog) log).switchTo(source); + if (log instanceof DeferredLog deferredLog) { + deferredLog.switchTo(source); } }); logs.clear(); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java index cad919111d..24ce4bbbad 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/ChangeableUrls.java @@ -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. @@ -102,8 +102,8 @@ final class ChangeableUrls implements Iterable { } private static URL[] urlsFromClassLoader(ClassLoader classLoader) { - if (classLoader instanceof URLClassLoader) { - return ((URLClassLoader) classLoader).getURLs(); + if (classLoader instanceof URLClassLoader urlClassLoader) { + return urlClassLoader.getURLs(); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) .map(ChangeableUrls::toURL).toArray(URL[]::new); diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java index 6969c99e61..11d8b8b700 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartApplicationListener.java @@ -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. @@ -46,17 +46,17 @@ public class RestartApplicationListener implements ApplicationListener urls = new LinkedHashSet<>(); ClassLoader classLoader = this.classLoader; while (classLoader != null) { - if (classLoader instanceof URLClassLoader) { - Collections.addAll(urls, ((URLClassLoader) classLoader).getURLs()); + if (classLoader instanceof URLClassLoader urlClassLoader) { + Collections.addAll(urls, urlClassLoader.getURLs()); } classLoader = classLoader.getParent(); } diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java index 689273c4ab..228a41779c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/test/MockClientHttpRequestFactory.java @@ -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. @@ -90,8 +90,8 @@ public class MockClientHttpRequestFactory implements ClientHttpRequestFactory { protected ClientHttpResponse executeInternal() throws IOException { MockClientHttpRequestFactory.this.executedRequests.add(this); Object response = MockClientHttpRequestFactory.this.responses.pollFirst(); - if (response instanceof IOException) { - throw (IOException) response; + if (response instanceof IOException ioException) { + throw ioException; } if (response == null) { response = new Response(0, null, HttpStatus.GONE); diff --git a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java index c659610747..aeccd3104d 100644 --- a/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java +++ b/spring-boot-project/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationListener.java @@ -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. @@ -51,8 +51,8 @@ public class PropertiesMigrationListener implements ApplicationListener source = new HashMap<>(); source.put("spring.datasource.schema-username", ""); source.put("spring.sql.init.username", ""); - ((ConfigurableEnvironment) environment).getPropertySources() - .addFirst(new MapPropertySource("testDatabase", source)); + configurableEnvironment.getPropertySources().addFirst(new MapPropertySource("testDatabase", source)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java index d3432e3f3f..770bcaef04 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySource.java @@ -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. @@ -134,8 +134,7 @@ public class AnnotationsPropertySource extends EnumerablePropertySource putProperties(name + "[" + i + "]", defaultSkip, array[i], properties); } } - else if (value instanceof MergedAnnotation) { - MergedAnnotation annotation = (MergedAnnotation) value; + else if (value instanceof MergedAnnotation annotation) { for (Method attribute : annotation.getType().getDeclaredMethods()) { collectProperties(name, defaultSkip, (MergedAnnotation) value, attribute, properties); } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java index f2007a56d5..5b91ef38e4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebDriverScope.java @@ -96,8 +96,8 @@ public class WebDriverScope implements Scope { synchronized (this.instances) { for (Object instance : this.instances.values()) { reset = true; - if (instance instanceof WebDriver) { - ((WebDriver) instance).quit(); + if (instance instanceof WebDriver webDriver) { + webDriver.quit(); } } this.instances.clear(); @@ -138,9 +138,9 @@ public class WebDriverScope implements Scope { * @return the web driver scope or {@code null} */ static WebDriverScope getFrom(ApplicationContext context) { - if (context instanceof ConfigurableApplicationContext) { - Scope scope = ((ConfigurableApplicationContext) context).getBeanFactory().getRegisteredScope(NAME); - return (scope instanceof WebDriverScope) ? (WebDriverScope) scope : null; + if (context instanceof ConfigurableApplicationContext configurableContext) { + Scope scope = configurableContext.getBeanFactory().getRegisteredScope(NAME); + return (scope instanceof WebDriverScope webDriverScope) ? webDriverScope : null; } return null; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java index e068632bd2..b662aec7a1 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/ImportsContextCustomizer.java @@ -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. @@ -94,11 +94,11 @@ class ImportsContextCustomizer implements ContextCustomizer { } private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { - if (context instanceof BeanDefinitionRegistry) { - return (BeanDefinitionRegistry) context; + if (context instanceof BeanDefinitionRegistry beanDefinitionRegistry) { + return beanDefinitionRegistry; } - if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); + if (context instanceof AbstractApplicationContext abstractContext) { + return (BeanDefinitionRegistry) abstractContext.getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } @@ -284,8 +284,8 @@ class ImportsContextCustomizer implements ContextCustomizer { } private Class[] getImports(Annotation annotation) { - if (annotation instanceof Import) { - return ((Import) annotation).value(); + if (annotation instanceof Import importAnnotation) { + return importAnnotation.value(); } return NO_IMPORTS; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java index 3e0e48bf44..f3aebd1986 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java @@ -296,8 +296,8 @@ public class SpringBootContextLoader extends AbstractContextLoader { @Override public void initialize(ConfigurableApplicationContext applicationContext) { - if (applicationContext instanceof ConfigurableWebApplicationContext) { - this.delegate.initialize((ConfigurableWebApplicationContext) applicationContext); + if (applicationContext instanceof ConfigurableWebApplicationContext webApplicationContext) { + this.delegate.initialize(webApplicationContext); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestArgs.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestArgs.java index 750754cb25..64e91d38fc 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestArgs.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestArgs.java @@ -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. @@ -69,8 +69,8 @@ class SpringBootTestArgs implements ContextCustomizer { */ static String[] get(Set customizers) { for (ContextCustomizer customizer : customizers) { - if (customizer instanceof SpringBootTestArgs) { - return ((SpringBootTestArgs) customizer).args; + if (customizer instanceof SpringBootTestArgs testArgs) { + return testArgs.args; } } return NO_ARGS; diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java index 8d226b04ac..d4c13e5613 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/ApplicationContextAssert.java @@ -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. @@ -298,8 +298,8 @@ public class ApplicationContextAssert private boolean isPrimary(String name, Scope scope) { ApplicationContext context = getApplicationContext(); while (context != null) { - if (context instanceof ConfigurableApplicationContext) { - ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) context).getBeanFactory(); + if (context instanceof ConfigurableApplicationContext configurableContext) { + ConfigurableListableBeanFactory factory = configurableContext.getBeanFactory(); if (factory.containsBean(name) && factory.getMergedBeanDefinition(name).isPrimary()) { return true; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java index 872145a1d8..6ed4a08305 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/assertj/AssertProviderApplicationContextInvocationHandler.java @@ -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. @@ -46,9 +46,9 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan AssertProviderApplicationContextInvocationHandler(Class applicationContextType, Supplier contextSupplier) { this.applicationContextType = applicationContextType; Object contextOrStartupFailure = getContextOrStartupFailure(contextSupplier); - if (contextOrStartupFailure instanceof RuntimeException) { + if (contextOrStartupFailure instanceof RuntimeException runtimeException) { this.applicationContext = null; - this.startupFailure = (RuntimeException) contextOrStartupFailure; + this.startupFailure = runtimeException; } else { this.applicationContext = (ApplicationContext) contextOrStartupFailure; @@ -136,8 +136,8 @@ class AssertProviderApplicationContextInvocationHandler implements InvocationHan } private Object invokeClose() throws IOException { - if (this.applicationContext instanceof Closeable) { - ((Closeable) this.applicationContext).close(); + if (this.applicationContext instanceof Closeable closeable) { + closeable.close(); } return null; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java index b90a317426..01b46d68b4 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java @@ -392,11 +392,10 @@ public abstract class AbstractApplicationContextRunner "Duplicate " + type + " definition " + definition); - if (element instanceof Field) { - Field field = (Field) element; + if (element instanceof Field field) { this.definitionFields.put(definition, field); } } @@ -114,8 +113,7 @@ class DefinitionsParser { for (Class clazz : value) { types.add(ResolvableType.forClass(clazz)); } - if (types.isEmpty() && element instanceof Field) { - Field field = (Field) element; + if (types.isEmpty() && element instanceof Field field) { types.add((field.getGenericType() instanceof TypeVariable) ? ResolvableType.forField(field, source) : ResolvableType.forField(field)); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java index afccd5926c..382f11d3de 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java @@ -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 enum MockReset { MockCreationSettings settings = mockingDetails.getMockCreationSettings(); List listeners = settings.getInvocationListeners(); for (Object listener : listeners) { - if (listener instanceof ResetInvocationListener) { - reset = ((ResetInvocationListener) listener).getReset(); + if (listener instanceof ResetInvocationListener resetInvocationListener) { + reset = resetInvocationListener.getReset(); } } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java index 93d0c4acf0..a739c36442 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java @@ -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 MockitoContextCustomizer implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedContextConfiguration) { - if (context instanceof BeanDefinitionRegistry) { - MockitoPostProcessor.register((BeanDefinitionRegistry) context, this.definitions); + if (context instanceof BeanDefinitionRegistry registry) { + MockitoPostProcessor.register(registry, this.definitions); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java index c87a9e6a71..1e0d5cb143 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java @@ -163,11 +163,11 @@ public class MockitoPostProcessor implements InstantiationAwareBeanPostProcessor private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, Definition definition, Field field) { - if (definition instanceof MockDefinition) { - registerMock(beanFactory, registry, (MockDefinition) definition, field); + if (definition instanceof MockDefinition mockDefinition) { + registerMock(beanFactory, registry, mockDefinition, field); } - else if (definition instanceof SpyDefinition) { - registerSpy(beanFactory, registry, (SpyDefinition) definition, field); + else if (definition instanceof SpyDefinition spyDefinition) { + registerSpy(beanFactory, registry, spyDefinition, field); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java index c1c6e41725..a46c659594 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java @@ -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,8 +73,8 @@ public class MockitoTestExecutionListener extends AbstractTestExecutionListener @Override public void afterTestMethod(TestContext testContext) throws Exception { Object mocks = testContext.getAttribute(MOCKS_ATTRIBUTE_NAME); - if (mocks instanceof AutoCloseable) { - ((AutoCloseable) mocks).close(); + if (mocks instanceof AutoCloseable closeable) { + closeable.close(); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java index ecbd376a6e..b2bab55fea 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java @@ -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. @@ -78,8 +78,7 @@ class QualifierDefinition { } static QualifierDefinition forElement(AnnotatedElement element) { - if (element != null && element instanceof Field) { - Field field = (Field) element; + if (element != null && element instanceof Field field) { Set annotations = getQualifierAnnotations(field); if (!annotations.isEmpty()) { return new QualifierDefinition(field, annotations); diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java index 2033c2e648..7a7f94cb7a 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java @@ -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. @@ -66,8 +66,8 @@ public class ResetMocksTestExecutionListener extends AbstractTestExecutionListen } private void resetMocks(ApplicationContext applicationContext, MockReset reset) { - if (applicationContext instanceof ConfigurableApplicationContext) { - resetMocks((ConfigurableApplicationContext) applicationContext, reset); + if (applicationContext instanceof ConfigurableApplicationContext configurableContext) { + resetMocks(configurableContext, reset); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java index f35a610df8..9f98bfacbd 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCapture.java @@ -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. @@ -208,8 +208,8 @@ class OutputCapture implements CapturedOutput { } private static PrintStream getSystemStream(PrintStream printStream) { - while (printStream instanceof PrintStreamCapture) { - printStream = ((PrintStreamCapture) printStream).getParent(); + while (printStream instanceof PrintStreamCapture printStreamCapture) { + printStream = printStreamCapture.getParent(); } return printStream; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/ApplicationContextTestUtils.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/ApplicationContextTestUtils.java index 6593df0eec..f27cb44f21 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/ApplicationContextTestUtils.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/util/ApplicationContextTestUtils.java @@ -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. @@ -33,8 +33,8 @@ public abstract class ApplicationContextTestUtils { */ public static void closeAll(ApplicationContext context) { if (context != null) { - if (context instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) context).close(); + if (context instanceof ConfigurableApplicationContext configurableContext) { + configurableContext.close(); } closeAll(context.getParent()); } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java index 5dc9fe4502..d98cc20932 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/SpringBootTestRandomPortEnvironmentPostProcessor.java @@ -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. @@ -89,8 +89,8 @@ class SpringBootTestRandomPortEnvironmentPostProcessor implements EnvironmentPos return environment.getConversionService().convert(value, Integer.class); } catch (ConversionFailedException ex) { - if (value instanceof String) { - return getResolvedValueIfPossible(environment, (String) value); + if (value instanceof String string) { + return getResolvedValueIfPossible(environment, string); } throw ex; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java index 9be8ceb63a..6905c74e83 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManager.java @@ -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. @@ -96,9 +96,9 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag URI uri; try { uri = new URI(replacementUri); - if (request instanceof MockClientHttpRequest) { - ((MockClientHttpRequest) request).setURI(uri); - return request; + if (request instanceof MockClientHttpRequest mockClientHttpRequest) { + mockClientHttpRequest.setURI(uri); + return mockClientHttpRequest; } return new ReplaceUriClientHttpRequest(uri, request); } @@ -158,9 +158,8 @@ public class RootUriRequestExpectationManager implements RequestExpectationManag RequestExpectationManager expectationManager) { Assert.notNull(restTemplate, "RestTemplate must not be null"); UriTemplateHandler templateHandler = restTemplate.getUriTemplateHandler(); - if (templateHandler instanceof RootUriTemplateHandler) { - return new RootUriRequestExpectationManager(((RootUriTemplateHandler) templateHandler).getRootUri(), - expectationManager); + if (templateHandler instanceof RootUriTemplateHandler rootHandler) { + return new RootUriRequestExpectationManager(rootHandler.getRootUri(), expectationManager); } return expectationManager; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java index 15193399bb..8aca5272da 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java @@ -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. @@ -163,8 +163,8 @@ public class TestRestTemplate { */ public String getRootUri() { UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler(); - if (uriTemplateHandler instanceof RootUriTemplateHandler) { - return ((RootUriTemplateHandler) uriTemplateHandler).getRootUri(); + if (uriTemplateHandler instanceof RootUriTemplateHandler rootHandler) { + return rootHandler.getRootUri(); } return ""; } @@ -941,8 +941,8 @@ public class TestRestTemplate { private URI applyRootUriIfNecessary(URI uri) { UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler(); - if ((uriTemplateHandler instanceof RootUriTemplateHandler) && uri.toString().startsWith("/")) { - return URI.create(((RootUriTemplateHandler) uriTemplateHandler).getRootUri() + uri.toString()); + if ((uriTemplateHandler instanceof RootUriTemplateHandler rootHandler) && uri.toString().startsWith("/")) { + return URI.create(rootHandler.getRootUri() + uri.toString()); } return uri; } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java index e8af8a4730..027f75eae1 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplateContextCustomizer.java @@ -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,8 +61,8 @@ class TestRestTemplateContextCustomizer implements ContextCustomizer { private void registerTestRestTemplate(ConfigurableApplicationContext context) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - if (beanFactory instanceof BeanDefinitionRegistry) { - registerTestRestTemplate((BeanDefinitionRegistry) beanFactory); + if (beanFactory instanceof BeanDefinitionRegistry registry) { + registerTestRestTemplate(registry); } } diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java index 77e7c89fe7..3d90095d08 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/WebTestClientContextCustomizer.java @@ -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. @@ -67,8 +67,8 @@ class WebTestClientContextCustomizer implements ContextCustomizer { private void registerWebTestClient(ConfigurableApplicationContext context) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - if (beanFactory instanceof BeanDefinitionRegistry) { - registerWebTestClient((BeanDefinitionRegistry) beanFactory); + if (beanFactory instanceof BeanDefinitionRegistry registry) { + registerWebTestClient(registry); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java index 8cdbbe05fd..7aad5701fb 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/TestDefaultTestExecutionListenersPostProcessor.java @@ -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. @@ -42,8 +42,7 @@ public class TestDefaultTestExecutionListenersPostProcessor implements DefaultTe @Override public void prepareTestInstance(TestContext testContext) throws Exception { Object testInstance = testContext.getTestInstance(); - if (testInstance instanceof SpringBootTestContextBootstrapperIntegrationTests) { - SpringBootTestContextBootstrapperIntegrationTests test = (SpringBootTestContextBootstrapperIntegrationTests) testInstance; + if (testInstance instanceof SpringBootTestContextBootstrapperIntegrationTests test) { test.defaultTestExecutionListenersPostProcessorCalled = true; } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java index 5d84902dda..aac2dacb96 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java @@ -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. @@ -56,8 +56,8 @@ class MockBeanContextCachingTests { Map contexts = (Map) ReflectionTestUtils .getField(this.contextCache, "contextMap"); for (ApplicationContext context : contexts.values()) { - if (context instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) context).close(); + if (context instanceof ConfigurableApplicationContext configurableContext) { + configurableContext.close(); } } this.contextCache.clear(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java index 68cedc92b0..64b1b2de59 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/AutoConfigureAnnotationProcessor.java @@ -213,8 +213,8 @@ public class AutoConfigureAnnotationProcessor extends AbstractProcessor { } private Object extractValue(Object value) { - if (value instanceof DeclaredType) { - return Elements.getQualifiedName(((DeclaredType) value).asElement()); + if (value instanceof DeclaredType declaredType) { + return Elements.getQualifiedName(declaredType.asElement()); } return value; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java index c2597a7d96..dc47df1722 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-autoconfigure-processor/src/main/java/org/springframework/boot/autoconfigureprocessor/Elements.java @@ -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. @@ -38,19 +38,18 @@ final class Elements { return getQualifiedName(enclosingElement) + "$" + ((DeclaredType) element.asType()).asElement().getSimpleName().toString(); } - if (element instanceof TypeElement) { - return ((TypeElement) element).getQualifiedName().toString(); + if (element instanceof TypeElement typeElement) { + return typeElement.getQualifiedName().toString(); } } return null; } private static TypeElement getEnclosingTypeElement(TypeMirror type) { - if (type instanceof DeclaredType) { - DeclaredType declaredType = (DeclaredType) type; + if (type instanceof DeclaredType declaredType) { Element enclosingElement = declaredType.asElement().getEnclosingElement(); - if (enclosingElement instanceof TypeElement) { - return (TypeElement) enclosingElement; + if (enclosingElement instanceof TypeElement typeElement) { + return typeElement; } } return null; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Binding.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Binding.java index 1c5e9647ba..8930f4fffd 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Binding.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/Binding.java @@ -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. @@ -39,10 +39,9 @@ public final class Binding { if (this == obj) { return true; } - if (!(obj instanceof Binding)) { + if (!(obj instanceof Binding binding)) { return false; } - Binding binding = (Binding) obj; return Objects.equals(this.value, binding.value); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java index 51b7dd0181..14dd9398a6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java @@ -55,11 +55,11 @@ public class InspectedContent implements Content { @Override public void writeTo(OutputStream outputStream) throws IOException { - if (this.content instanceof byte[]) { - FileCopyUtils.copy((byte[]) this.content, outputStream); + if (this.content instanceof byte[] bytes) { + FileCopyUtils.copy(bytes, outputStream); } - else if (this.content instanceof File) { - InputStream inputStream = new FileInputStream((File) this.content); + else if (this.content instanceof File file) { + InputStream inputStream = new FileInputStream(file); FileCopyUtils.copy(inputStream, outputStream); } else { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java index b06c693cd6..1971074ae5 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/JsonReader.java @@ -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. @@ -48,11 +48,11 @@ class JsonReader { return new RawConfigurationMetadata(groups, items, hints); } catch (Exception ex) { - if (ex instanceof IOException) { - throw (IOException) ex; + if (ex instanceof IOException ioException) { + throw ioException; } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; + if (ex instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(ex); } @@ -185,8 +185,7 @@ class JsonReader { } private Object readItemValue(Object value) throws Exception { - if (value instanceof JSONArray) { - JSONArray array = (JSONArray) value; + if (value instanceof JSONArray array) { Object[] content = new Object[array.length()]; for (int i = 0; i < array.length(); i++) { content[i] = array.get(i); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java index 5f6e617adb..05ba191e24 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java @@ -212,11 +212,11 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor AnnotationMirror annotation = this.metadataEnv.getConfigurationPropertiesAnnotation(element); if (annotation != null) { String prefix = getPrefix(annotation); - if (element instanceof TypeElement) { - processAnnotatedTypeElement(prefix, (TypeElement) element, new Stack<>()); + if (element instanceof TypeElement typeElement) { + processAnnotatedTypeElement(prefix, typeElement, new Stack<>()); } - else if (element instanceof ExecutableElement) { - processExecutableElement(prefix, (ExecutableElement) element, new Stack<>()); + else if (element instanceof ExecutableElement executableElement) { + processExecutableElement(prefix, executableElement, new Stack<>()); } } } @@ -235,7 +235,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor if ((!element.getModifiers().contains(Modifier.PRIVATE)) && (TypeKind.VOID != element.getReturnType().getKind())) { Element returns = this.processingEnv.getTypeUtils().asElement(element.getReturnType()); - if (returns instanceof TypeElement) { + if (returns instanceof TypeElement typeElement) { ItemMetadata group = ItemMetadata.newGroup(prefix, this.metadataEnv.getTypeUtils().getQualifiedName(returns), this.metadataEnv.getTypeUtils().getQualifiedName(element.getEnclosingElement()), @@ -246,7 +246,7 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } else { this.metadataCollector.add(group); - processTypeElement(prefix, (TypeElement) returns, element, seen); + processTypeElement(prefix, typeElement, element, seen); } } } @@ -273,8 +273,8 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor try { String annotationName = this.metadataEnv.getTypeUtils().getQualifiedName(annotations.get(0)); AnnotationMirror annotation = this.metadataEnv.getAnnotation(element, annotationName); - if (element instanceof TypeElement) { - processEndpoint(annotation, (TypeElement) element); + if (element instanceof TypeElement typeElement) { + processEndpoint(annotation, typeElement); } } catch (Exception ex) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java index 3e2810e318..e625be9453 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java @@ -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. @@ -284,8 +284,7 @@ class TypeUtils { public String visitTypeVariable(TypeVariable t, TypeDescriptor descriptor) { TypeMirror typeMirror = descriptor.resolveGeneric(t); if (typeMirror != null) { - if (typeMirror instanceof TypeVariable) { - TypeVariable typeVariable = (TypeVariable) typeMirror; + if (typeMirror instanceof TypeVariable typeVariable) { // Still unresolved, let's use the upper bound, checking first if // a cycle may exist if (!hasCycle(typeVariable)) { @@ -302,9 +301,8 @@ class TypeUtils { private boolean hasCycle(TypeVariable variable) { TypeMirror upperBound = variable.getUpperBound(); - if (upperBound instanceof DeclaredType) { - return ((DeclaredType) upperBound).getTypeArguments().stream() - .anyMatch((candidate) -> candidate.equals(variable)); + if (upperBound instanceof DeclaredType declaredType) { + return declaredType.getTypeArguments().stream().anyMatch((candidate) -> candidate.equals(variable)); } return false; } @@ -333,18 +331,17 @@ class TypeUtils { return getQualifiedName(enclosingElement) + "$" + ((DeclaredType) element.asType()).asElement().getSimpleName(); } - if (element instanceof TypeElement) { - return ((TypeElement) element).getQualifiedName().toString(); + if (element instanceof TypeElement typeElement) { + return typeElement.getQualifiedName().toString(); } throw new IllegalStateException("Could not extract qualified name from " + element); } private TypeElement getEnclosingTypeElement(TypeMirror type) { - if (type instanceof DeclaredType) { - DeclaredType declaredType = (DeclaredType) type; + if (type instanceof DeclaredType declaredType) { Element enclosingElement = declaredType.asElement().getEnclosingElement(); - if (enclosingElement instanceof TypeElement) { - return (TypeElement) enclosingElement; + if (enclosingElement instanceof TypeElement typeElement) { + return typeElement; } } return null; @@ -373,8 +370,7 @@ class TypeUtils { } private void registerIfNecessary(TypeMirror variable, TypeMirror resolution) { - if (variable instanceof TypeVariable) { - TypeVariable typeVariable = (TypeVariable) variable; + if (variable instanceof TypeVariable typeVariable) { if (this.generics.keySet().stream() .noneMatch((candidate) -> getParameterName(candidate).equals(getParameterName(typeVariable)))) { this.generics.put(typeVariable, resolution); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java index 7a6bcfb74e..53370badb6 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/JsonMarshaller.java @@ -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. @@ -52,11 +52,11 @@ public class JsonMarshaller { outputStream.write(object.toString(2).getBytes(StandardCharsets.UTF_8)); } catch (Exception ex) { - if (ex instanceof IOException) { - throw (IOException) ex; + if (ex instanceof IOException ioException) { + throw ioException; } - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; + if (ex instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(ex); } @@ -150,8 +150,7 @@ public class JsonMarshaller { } private Object readItemValue(Object value) throws Exception { - if (value instanceof JSONArray) { - JSONArray array = (JSONArray) value; + if (value instanceof JSONArray array) { Object[] content = new Object[array.length()]; for (int i = 0; i < array.length(); i++) { content[i] = array.get(i); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java index 883d2542b3..47938fee85 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/fieldvalues/AbstractFieldValuesProcessorTests.java @@ -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. @@ -126,9 +126,9 @@ public abstract class AbstractFieldValuesProcessorTests { public boolean process(Set annotations, RoundEnvironment roundEnv) { for (TypeElement annotation : annotations) { for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { - if (element instanceof TypeElement) { + if (element instanceof TypeElement typeElement) { try { - this.values.putAll(this.processor.getFieldValues((TypeElement) element)); + this.values.putAll(this.processor.getFieldValues(typeElement)); } catch (Exception ex) { throw new IllegalStateException(ex); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java index 467a33746f..c56a63c4f2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java @@ -264,10 +264,9 @@ final class JavaPluginAction implements PluginApplicationAction { @Override public void execute(Task task) { - if (!(task instanceof JavaCompile)) { + if (!(task instanceof JavaCompile compile)) { return; } - JavaCompile compile = (JavaCompile) task; if (hasConfigurationProcessorOnClasspath(compile)) { configureAdditionalMetadataLocations(compile); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/util/VersionExtractor.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/util/VersionExtractor.java index 72e779b8f9..3e3399c8a1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/util/VersionExtractor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/util/VersionExtractor.java @@ -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. @@ -49,8 +49,8 @@ public final class VersionExtractor { URL codeSourceLocation = cls.getProtectionDomain().getCodeSource().getLocation(); try { URLConnection connection = codeSourceLocation.openConnection(); - if (connection instanceof JarURLConnection) { - return getImplementationVersion(((JarURLConnection) connection).getJarFile()); + if (connection instanceof JarURLConnection jarURLConnection) { + return getImplementationVersion(jarURLConnection.getJarFile()); } try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) { return getImplementationVersion(jarFile); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/Context.java b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/Context.java index 168e3d3148..ae07f1a1f0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/Context.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-jarmode-layertools/src/main/java/org/springframework/boot/jarmode/layertools/Context.java @@ -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,8 +88,8 @@ class Context { private static File findSource(URL location) throws IOException, URISyntaxException { URLConnection connection = location.openConnection(); - if (connection instanceof JarURLConnection) { - return getRootJarFile(((JarURLConnection) connection).getJarFile()); + if (connection instanceof JarURLConnection jarURLConnection) { + return getRootJarFile(jarURLConnection.getJarFile()); } return new File(location.toURI()); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java index d135d64d03..b70bf1b563 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/DefaultLaunchScript.java @@ -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. @@ -113,8 +113,8 @@ public class DefaultLaunchScript implements LaunchScript { } private String parseFilePropertyValue(Object propertyValue) throws IOException { - if (propertyValue instanceof File) { - return loadContent((File) propertyValue); + if (propertyValue instanceof File file) { + return loadContent(file); } return loadContent(new File(propertyValue.toString())); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java index c45ee567ac..4baa920870 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/JarWriter.java @@ -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. @@ -99,8 +99,8 @@ public class JarWriter extends AbstractJarWriter implements AutoCloseable { } private JarArchiveEntry asJarArchiveEntry(ZipEntry entry) throws ZipException { - if (entry instanceof JarArchiveEntry) { - return (JarArchiveEntry) entry; + if (entry instanceof JarArchiveEntry jarArchiveEntry) { + return jarArchiveEntry; } return new JarArchiveEntry(entry); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java index ce334293a3..a448311726 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java @@ -205,8 +205,8 @@ public abstract class Packager { private void writeLoaderClasses(AbstractJarWriter writer) throws IOException { Layout layout = getLayout(); - if (layout instanceof CustomLoaderLayout) { - ((CustomLoaderLayout) getLayout()).writeLoadedClasses(writer); + if (layout instanceof CustomLoaderLayout customLoaderLayout) { + customLoaderLayout.writeLoadedClasses(writer); } else if (layout.isExecutable()) { writer.writeLoaderClasses(); @@ -223,8 +223,8 @@ public abstract class Packager { } private EntryTransformer getEntityTransformer() { - if (getLayout() instanceof RepackagingLayout) { - return new RepackagingEntryTransformer((RepackagingLayout) getLayout()); + if (getLayout() instanceof RepackagingLayout repackagingLayout) { + return new RepackagingEntryTransformer(repackagingLayout); } return EntryTransformer.NONE; } @@ -349,8 +349,8 @@ public abstract class Packager { private void addBootAttributesForLayout(Attributes attributes) { Layout layout = getLayout(); - if (layout instanceof RepackagingLayout) { - attributes.putValue(BOOT_CLASSES_ATTRIBUTE, ((RepackagingLayout) layout).getRepackagedClassesLocation()); + if (layout instanceof RepackagingLayout repackagingLayout) { + attributes.putValue(BOOT_CLASSES_ATTRIBUTE, repackagingLayout.getRepackagedClassesLocation()); } else { attributes.putValue(BOOT_CLASSES_ATTRIBUTE, layout.getClassesLocation()); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SizeCalculatingEntryWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SizeCalculatingEntryWriter.java index 1fbb23b8c5..36d13c65b2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SizeCalculatingEntryWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/SizeCalculatingEntryWriter.java @@ -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. @@ -60,8 +60,8 @@ final class SizeCalculatingEntryWriter implements EntryWriter { } private InputStream getContentInputStream() throws FileNotFoundException { - if (this.content instanceof File) { - return new FileInputStream((File) this.content); + if (this.content instanceof File file) { + return new FileInputStream(file); } return new ByteArrayInputStream((byte[]) this.content); } @@ -110,8 +110,8 @@ final class SizeCalculatingEntryWriter implements EntryWriter { @Override public void write(byte[] b, int off, int len) throws IOException { int updatedSize = this.size + len; - if (updatedSize > THRESHOLD && this.outputStream instanceof ByteArrayOutputStream) { - this.outputStream = convertToFileOutputStream((ByteArrayOutputStream) this.outputStream); + if (updatedSize > THRESHOLD && this.outputStream instanceof ByteArrayOutputStream byteArrayOutputStream) { + this.outputStream = convertToFileOutputStream(byteArrayOutputStream); } this.outputStream.write(b, off, len); this.size = updatedSize; @@ -137,8 +137,8 @@ final class SizeCalculatingEntryWriter implements EntryWriter { } Object getContent() { - return (this.outputStream instanceof ByteArrayOutputStream) - ? ((ByteArrayOutputStream) this.outputStream).toByteArray() : this.tempFile; + return (this.outputStream instanceof ByteArrayOutputStream byteArrayOutputStream) + ? byteArrayOutputStream.toByteArray() : this.tempFile; } int getSize() { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java index 6089a76b45..8c7cf98ae1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/LaunchedURLClassLoader.java @@ -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. @@ -217,8 +217,8 @@ public class LaunchedURLClassLoader extends URLClassLoader { for (URL url : getURLs()) { try { URLConnection connection = url.openConnection(); - if (connection instanceof JarURLConnection) { - JarFile jarFile = ((JarURLConnection) connection).getJarFile(); + if (connection instanceof JarURLConnection jarURLConnection) { + JarFile jarFile = jarURLConnection.getJarFile(); if (jarFile.getEntry(classEntryName) != null && jarFile.getEntry(packageEntryName) != null && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java index a84c01139e..be1876c612 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java @@ -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. @@ -269,8 +269,8 @@ public class PropertiesLauncher extends Launcher { } catch (IOException ex) { // Close the HTTP connection (if applicable). - if (con instanceof HttpURLConnection) { - ((HttpURLConnection) con).disconnect(); + if (con instanceof HttpURLConnection httpURLConnection) { + httpURLConnection.disconnect(); } throw ex; } @@ -283,8 +283,7 @@ public class PropertiesLauncher extends Launcher { URLConnection connection = url.openConnection(); try { connection.setUseCaches(connection.getClass().getSimpleName().startsWith("JNLP")); - if (connection instanceof HttpURLConnection) { - HttpURLConnection httpConnection = (HttpURLConnection) connection; + if (connection instanceof HttpURLConnection httpConnection) { httpConnection.setRequestMethod("HEAD"); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { @@ -297,8 +296,8 @@ public class PropertiesLauncher extends Launcher { return (connection.getContentLength() >= 0); } finally { - if (connection instanceof HttpURLConnection) { - ((HttpURLConnection) connection).disconnect(); + if (connection instanceof HttpURLConnection httpURLConnection) { + httpURLConnection.disconnect(); } } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java index fad95b607e..8b5a09ca2b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/Handler.java @@ -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. @@ -109,13 +109,13 @@ public class Handler extends URLStreamHandler { return (connection != null) ? connection : openFallbackHandlerConnection(url); } catch (Exception ex) { - if (reason instanceof IOException) { + if (reason instanceof IOException ioException) { log(false, "Unable to open fallback handler", ex); - throw (IOException) reason; + throw ioException; } log(true, "Unable to open fallback handler", ex); - if (reason instanceof RuntimeException) { - throw (RuntimeException) reason; + if (reason instanceof RuntimeException runtimeException) { + throw runtimeException; } throw new IllegalStateException(reason); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java index 65727df35d..91c2cadf9a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFile.java @@ -278,8 +278,8 @@ public class JarFile extends AbstractJarFile implements Iterable { T entry = doGetEntry(name, type, cacheEntry, null); if (!isMetaInfEntry(name) && isMultiReleaseJar()) { int version = RUNTIME_VERSION; - AsciiBytes nameAlias = (entry instanceof JarEntry) ? ((JarEntry) entry).getAsciiBytesName() + AsciiBytes nameAlias = (entry instanceof JarEntry jarEntry) ? jarEntry.getAsciiBytesName() : new AsciiBytes(name.toString()); while (version > BASE_VERSION) { T versionedEntry = doGetEntry("META-INF/versions/" + version + "/" + name, type, cacheEntry, nameAlias); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java index d5c2f2ca47..d624f85bb1 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/JarFileWrapper.java @@ -113,11 +113,11 @@ class JarFileWrapper extends AbstractJarFile { } static JarFile unwrap(java.util.jar.JarFile jarFile) { - if (jarFile instanceof JarFile) { - return (JarFile) jarFile; + if (jarFile instanceof JarFile file) { + return file; } - if (jarFile instanceof JarFileWrapper) { - return unwrap(((JarFileWrapper) jarFile).parent); + if (jarFile instanceof JarFileWrapper wrapper) { + return unwrap(wrapper.parent); } throw new IllegalStateException("Not a JarFile or Wrapper"); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/StringSequence.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/StringSequence.java index b77492e562..9e6af077ed 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/StringSequence.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/StringSequence.java @@ -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. @@ -120,10 +120,9 @@ final class StringSequence implements CharSequence { if (this == obj) { return true; } - if (!(obj instanceof CharSequence)) { + if (!(obj instanceof CharSequence other)) { return false; } - CharSequence other = (CharSequence) obj; int n = length(); if (n != other.length()) { return false; diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java index 2889520bd4..93d5e0b01d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/CustomLayersProvider.java @@ -108,8 +108,8 @@ class CustomLayersProvider { NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); - if (child instanceof Element) { - ContentSelector selector = selectorFactory.apply((Element) child); + if (child instanceof Element childElement) { + ContentSelector selector = selectorFactory.apply(childElement); selectors.add(selector); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JavaCompilerPluginConfiguration.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JavaCompilerPluginConfiguration.java index b44be9a06d..a7a12f447b 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JavaCompilerPluginConfiguration.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JavaCompilerPluginConfiguration.java @@ -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. @@ -59,8 +59,7 @@ class JavaCompilerPluginConfiguration { Plugin plugin = this.project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin"); if (plugin != null) { Object pluginConfiguration = plugin.getConfiguration(); - if (pluginConfiguration instanceof Xpp3Dom) { - Xpp3Dom dom = (Xpp3Dom) pluginConfiguration; + if (pluginConfiguration instanceof Xpp3Dom dom) { return getNodeValue(dom, propertyName); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/VersionExtractor.java b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/VersionExtractor.java index 41462ebf5a..ce83bf786d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/VersionExtractor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/VersionExtractor.java @@ -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. @@ -48,8 +48,8 @@ final class VersionExtractor { URL codeSourceLocation = cls.getProtectionDomain().getCodeSource().getLocation(); try { URLConnection connection = codeSourceLocation.openConnection(); - if (connection instanceof JarURLConnection) { - return getImplementationVersion(((JarURLConnection) connection).getJarFile()); + if (connection instanceof JarURLConnection jarURLConnection) { + return getImplementationVersion(jarURLConnection.getJarFile()); } try (JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) { return getImplementationVersion(jarFile); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java index 528e32c592..22077462d0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java @@ -115,8 +115,8 @@ final class ModifiedClassPathClassLoader extends URLClassLoader { } private static Stream doExtractUrls(ClassLoader classLoader) { - if (classLoader instanceof URLClassLoader) { - return Stream.of(((URLClassLoader) classLoader).getURLs()); + if (classLoader instanceof URLClassLoader urlClassLoader) { + return Stream.of(urlClassLoader.getURLs()); } return Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) .map(ModifiedClassPathClassLoader::toURL); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java index 4a60add574..fc817f4d23 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/system/OutputCapture.java @@ -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. @@ -193,8 +193,8 @@ class OutputCapture implements CapturedOutput { } private static PrintStream getSystemStream(PrintStream printStream) { - while (printStream instanceof PrintStreamCapture) { - printStream = ((PrintStreamCapture) printStream).getParent(); + while (printStream instanceof PrintStreamCapture printStreamCapture) { + printStream = printStreamCapture.getParent(); } return printStream; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java index e4e7885051..7534915ec6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java @@ -142,20 +142,20 @@ class BeanDefinitionLoader { private void load(Object source) { Assert.notNull(source, "Source must not be null"); - if (source instanceof Class) { - load((Class) source); + if (source instanceof Class clazz) { + load(clazz); return; } - if (source instanceof Resource) { - load((Resource) source); + if (source instanceof Resource resource) { + load(resource); return; } - if (source instanceof Package) { - load((Package) source); + if (source instanceof Package pack) { + load(pack); return; } - if (source instanceof CharSequence) { - load((CharSequence) source); + if (source instanceof CharSequence sequence) { + load(sequence); return; } throw new IllegalArgumentException("Invalid source type " + source.getClass()); @@ -234,8 +234,8 @@ class BeanDefinitionLoader { ResourceLoader loader = (this.resourceLoader != null) ? this.resourceLoader : new PathMatchingResourcePatternResolver(); try { - if (loader instanceof ResourcePatternResolver) { - return ((ResourcePatternResolver) loader).getResources(source); + if (loader instanceof ResourcePatternResolver resolver) { + return resolver.getResources(source); } return new Resource[] { loader.getResource(source) }; } @@ -248,12 +248,12 @@ class BeanDefinitionLoader { if (resource == null || !resource.exists()) { return false; } - if (resource instanceof ClassPathResource) { + if (resource instanceof ClassPathResource classPathResource) { // A simple package without a '.' may accidentally get loaded as an XML // document if we're not careful. The result of getInputStream() will be // a file list of the package content. We double-check here that it's not // actually a package. - String path = ((ClassPathResource) resource).getPath(); + String path = classPathResource.getPath(); if (path.indexOf('.') == -1) { try { return getClass().getClassLoader().getDefinedPackage(path) == null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java index 668697d4c7..85c88cdd13 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java @@ -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. @@ -52,8 +52,8 @@ public final class LazyInitializationBeanFactoryPostProcessor implements BeanFac Collection filters = getFilters(beanFactory); for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); - if (beanDefinition instanceof AbstractBeanDefinition) { - postProcess(beanFactory, filters, beanName, (AbstractBeanDefinition) beanDefinition); + if (beanDefinition instanceof AbstractBeanDefinition abstractBeanDefinition) { + postProcess(beanFactory, filters, beanName, abstractBeanDefinition); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index 9c4e44e28d..79875caf50 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -391,11 +391,10 @@ public class SpringApplication { if (printedBanner != null) { beanFactory.registerSingleton("springBootBanner", printedBanner); } - if (beanFactory instanceof AbstractAutowireCapableBeanFactory) { - ((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.allowCircularReferences); - if (beanFactory instanceof DefaultListableBeanFactory) { - ((DefaultListableBeanFactory) beanFactory) - .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); + if (beanFactory instanceof AbstractAutowireCapableBeanFactory autowireCapableBeanFactory) { + autowireCapableBeanFactory.setAllowCircularReferences(this.allowCircularReferences); + if (beanFactory instanceof DefaultListableBeanFactory listableBeanFactory) { + listableBeanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } } if (this.lazyInitialization) { @@ -582,11 +581,11 @@ public class SpringApplication { this.beanNameGenerator); } if (this.resourceLoader != null) { - if (context instanceof GenericApplicationContext) { - ((GenericApplicationContext) context).setResourceLoader(this.resourceLoader); + if (context instanceof GenericApplicationContext genericApplicationContext) { + genericApplicationContext.setResourceLoader(this.resourceLoader); } - if (context instanceof DefaultResourceLoader) { - ((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader()); + if (context instanceof DefaultResourceLoader defaultResourceLoader) { + defaultResourceLoader.setClassLoader(this.resourceLoader.getClassLoader()); } } if (this.addConversionService) { @@ -709,11 +708,11 @@ public class SpringApplication { * @return the BeanDefinitionRegistry if it can be determined */ private BeanDefinitionRegistry getBeanDefinitionRegistry(ApplicationContext context) { - if (context instanceof BeanDefinitionRegistry) { - return (BeanDefinitionRegistry) context; + if (context instanceof BeanDefinitionRegistry registry) { + return registry; } - if (context instanceof AbstractApplicationContext) { - return (BeanDefinitionRegistry) ((AbstractApplicationContext) context).getBeanFactory(); + if (context instanceof AbstractApplicationContext abstractApplicationContext) { + return (BeanDefinitionRegistry) abstractApplicationContext.getBeanFactory(); } throw new IllegalStateException("Could not locate BeanDefinitionRegistry"); } @@ -750,11 +749,11 @@ public class SpringApplication { runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); for (Object runner : new LinkedHashSet<>(runners)) { - if (runner instanceof ApplicationRunner) { - callRunner((ApplicationRunner) runner, args); + if (runner instanceof ApplicationRunner applicationRunner) { + callRunner(applicationRunner, args); } - if (runner instanceof CommandLineRunner) { - callRunner((CommandLineRunner) runner, args); + if (runner instanceof CommandLineRunner commandLineRunner) { + callRunner(commandLineRunner, args); } } } @@ -875,8 +874,8 @@ public class SpringApplication { if (exception == null) { return 0; } - if (exception instanceof ExitCodeGenerator) { - return ((ExitCodeGenerator) exception).getExitCode(); + if (exception instanceof ExitCodeGenerator generator) { + return generator.getExitCode(); } return getExitCodeFromExitCodeGeneratorException(exception.getCause()); } @@ -1362,8 +1361,7 @@ public class SpringApplication { } private static void close(ApplicationContext context) { - if (context instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext closable = (ConfigurableApplicationContext) context; + if (context instanceof ConfigurableApplicationContext closable) { closable.close(); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java index cbef17201e..25fe02d57f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrar.java @@ -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,11 +98,11 @@ public class SpringApplicationAdminMXBeanRegistrar implements ApplicationContext @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ApplicationReadyEvent) { - onApplicationReadyEvent((ApplicationReadyEvent) event); + if (event instanceof ApplicationReadyEvent readyEvent) { + onApplicationReadyEvent(readyEvent); } - if (event instanceof WebServerInitializedEvent) { - onWebServerInitializedEvent((WebServerInitializedEvent) event); + if (event instanceof WebServerInitializedEvent initializedEvent) { + onWebServerInitializedEvent(initializedEvent); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java index bd34ec6736..742f6f8f99 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/builder/ParentContextCloserApplicationListener.java @@ -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,7 @@ public class ParentContextCloserApplicationListener } private void maybeInstallListenerInParent(ConfigurableApplicationContext child) { - if (child == this.context && child.getParent() instanceof ConfigurableApplicationContext) { - ConfigurableApplicationContext parent = (ConfigurableApplicationContext) child.getParent(); + if (child == this.context && child.getParent() instanceof ConfigurableApplicationContext parent) { parent.addApplicationListener(createContextCloserListener(child)); } } @@ -103,8 +102,7 @@ public class ParentContextCloserApplicationListener if (obj == null) { return false; } - if (obj instanceof ContextCloserListener) { - ContextCloserListener other = (ContextCloserListener) obj; + if (obj instanceof ContextCloserListener other) { return ObjectUtils.nullSafeEquals(this.childContext.get(), other.childContext.get()); } return super.equals(obj); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java index 674a8ff490..14d7c12f35 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/cloud/CloudPlatform.java @@ -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. @@ -100,8 +100,8 @@ public enum CloudPlatform { @Override public boolean isDetected(Environment environment) { - if (environment instanceof ConfigurableEnvironment) { - return isAutoDetected((ConfigurableEnvironment) environment); + if (environment instanceof ConfigurableEnvironment configurableEnvironment) { + return isAutoDetected(configurableEnvironment); } return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java index 488daf6c7e..235027a9ec 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java @@ -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. @@ -222,14 +222,14 @@ public class ApplicationPidFileWriter implements ApplicationListener target, BindContext context, Object result) { - if (result instanceof ConfigDataLocation) { - return withOrigin(context, (ConfigDataLocation) result); + if (result instanceof ConfigDataLocation location) { + return withOrigin(context, location); } if (result instanceof List) { List list = ((List) result).stream().filter(Objects::nonNull).collect(Collectors.toList()); for (int i = 0; i < list.size(); i++) { Object element = list.get(i); - if (element instanceof ConfigDataLocation) { - list.set(i, withOrigin(context, (ConfigDataLocation) element)); + if (element instanceof ConfigDataLocation location) { + list.set(i, withOrigin(context, location)); } } return list; } - if (result instanceof ConfigDataLocation[]) { - ConfigDataLocation[] locations = Arrays.stream((ConfigDataLocation[]) result).filter(Objects::nonNull) + if (result instanceof ConfigDataLocation[] unfilteredLocations) { + ConfigDataLocation[] locations = Arrays.stream(unfilteredLocations).filter(Objects::nonNull) .toArray(ConfigDataLocation[]::new); for (int i = 0; i < locations.length; i++) { locations[i] = withOrigin(context, locations[i]); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationResolvers.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationResolvers.java index 3a1a7709ec..b7a312a3f6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationResolvers.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataLocationResolvers.java @@ -71,8 +71,8 @@ class ConfigDataLocationResolvers { List> reordered = new ArrayList<>(resolvers.size()); StandardConfigDataLocationResolver resourceResolver = null; for (ConfigDataLocationResolver resolver : resolvers) { - if (resolver instanceof StandardConfigDataLocationResolver) { - resourceResolver = (StandardConfigDataLocationResolver) resolver; + if (resolver instanceof StandardConfigDataLocationResolver configDataLocationResolver) { + resourceResolver = configDataLocationResolver; } else { reordered.add(resolver); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzer.java index 2202d0fb9f..6da25d4616 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataNotFoundFailureAnalyzer.java @@ -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. @@ -49,11 +49,11 @@ class ConfigDataNotFoundFailureAnalyzer extends AbstractFailureAnalyzer> delegates = getListeners( - ((ApplicationEnvironmentPreparedEvent) event).getEnvironment()); + if (event instanceof ApplicationEnvironmentPreparedEvent preparedEvent) { + List> delegates = getListeners(preparedEvent.getEnvironment()); if (delegates.isEmpty()) { return; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java index 01b66aaaa9..89e623b714 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java @@ -170,8 +170,8 @@ public class StandardConfigDataLocationResolver return resourceLocation; } ConfigDataResource parent = context.getParent(); - if (parent instanceof StandardConfigDataResource) { - String parentResourceLocation = ((StandardConfigDataResource) parent).getReference().getResourceLocation(); + if (parent instanceof StandardConfigDataResource resource) { + String parentResourceLocation = resource.getReference().getResourceLocation(); String parentDirectory = parentResourceLocation.substring(0, parentResourceLocation.lastIndexOf("/") + 1); return parentDirectory + resourceLocation; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java index 79d1ec5d95..08432f5eed 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java @@ -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. @@ -95,8 +95,8 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, @Override public void contextLoaded(ConfigurableApplicationContext context) { for (ApplicationListener listener : this.application.getListeners()) { - if (listener instanceof ApplicationContextAware) { - ((ApplicationContextAware) listener).setApplicationContext(context); + if (listener instanceof ApplicationContextAware contextAware) { + contextAware.setApplicationContext(context); } context.addApplicationListener(listener); } @@ -126,9 +126,8 @@ public class EventPublishingRunListener implements SpringApplicationRunListener, else { // An inactive context may not have a multicaster so we use our multicaster to // call all of the context's listeners instead - if (context instanceof AbstractApplicationContext) { - for (ApplicationListener listener : ((AbstractApplicationContext) context) - .getApplicationListeners()) { + if (context instanceof AbstractApplicationContext abstractApplicationContext) { + for (ApplicationListener listener : abstractApplicationContext.getApplicationListeners()) { this.initialMulticaster.addApplicationListener(listener); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java index ff9cf76f7d..40cf76b07e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java @@ -209,17 +209,17 @@ public class LoggingApplicationListener implements GenericApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ApplicationStartingEvent) { - onApplicationStartingEvent((ApplicationStartingEvent) event); + if (event instanceof ApplicationStartingEvent startingEvent) { + onApplicationStartingEvent(startingEvent); } - else if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); + else if (event instanceof ApplicationEnvironmentPreparedEvent environmentPreparedEvent) { + onApplicationEnvironmentPreparedEvent(environmentPreparedEvent); } - else if (event instanceof ApplicationPreparedEvent) { - onApplicationPreparedEvent((ApplicationPreparedEvent) event); + else if (event instanceof ApplicationPreparedEvent preparedEvent) { + onApplicationPreparedEvent(preparedEvent); } - else if (event instanceof ContextClosedEvent - && ((ContextClosedEvent) event).getApplicationContext().getParent() == null) { + else if (event instanceof ContextClosedEvent contextClosedEvent + && contextClosedEvent.getApplicationContext().getParent() == null) { onContextClosedEvent(); } else if (event instanceof ApplicationFailedEvent) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java index 438d830c4a..009445a331 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java @@ -144,8 +144,8 @@ public final class ConfigurationPropertiesBean { */ public static Map getAll(ApplicationContext applicationContext) { Assert.notNull(applicationContext, "ApplicationContext must not be null"); - if (applicationContext instanceof ConfigurableApplicationContext) { - return getAll((ConfigurableApplicationContext) applicationContext); + if (applicationContext instanceof ConfigurableApplicationContext configurableContext) { + return getAll(configurableContext); } Map propertiesBeans = new LinkedHashMap<>(); applicationContext.getBeansWithAnnotation(ConfigurationProperties.class).forEach((beanName, bean) -> { @@ -213,8 +213,8 @@ public final class ConfigurationPropertiesBean { } private static Method findFactoryMethod(ApplicationContext applicationContext, String beanName) { - if (applicationContext instanceof ConfigurableApplicationContext) { - return findFactoryMethod((ConfigurableApplicationContext) applicationContext, beanName); + if (applicationContext instanceof ConfigurableApplicationContext configurableContext) { + return findFactoryMethod(configurableContext, beanName); } return null; } @@ -226,8 +226,8 @@ public final class ConfigurationPropertiesBean { private static Method findFactoryMethod(ConfigurableListableBeanFactory beanFactory, String beanName) { if (beanFactory.containsBeanDefinition(beanName)) { BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName); - if (beanDefinition instanceof RootBeanDefinition) { - Method resolvedFactoryMethod = ((RootBeanDefinition) beanDefinition).getResolvedFactoryMethod(); + if (beanDefinition instanceof RootBeanDefinition rootBeanDefinition) { + Method resolvedFactoryMethod = rootBeanDefinition.getResolvedFactoryMethod(); if (resolvedFactoryMethod != null) { return resolvedFactoryMethod; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java index 182d611a40..3ed035657e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanRegistrar.java @@ -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. @@ -75,8 +75,8 @@ final class ConfigurationPropertiesBeanRegistrar { && ((ListableBeanFactory) beanFactory).containsBeanDefinition(name)) { return true; } - if (beanFactory instanceof HierarchicalBeanFactory) { - return containsBeanDefinition(((HierarchicalBeanFactory) beanFactory).getParentBeanFactory(), name); + if (beanFactory instanceof HierarchicalBeanFactory hierarchicalBeanFactory) { + return containsBeanDefinition(hierarchicalBeanFactory.getParentBeanFactory(), name); } return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java index 597b67bc5c..e8a208ac56 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java @@ -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. @@ -144,8 +144,8 @@ class ConfigurationPropertiesBinder { if (this.jsr303Present && target.getAnnotation(Validated.class) != null) { validators.add(getJsr303Validator()); } - if (target.getValue() != null && target.getValue().get() instanceof Validator) { - validators.add((Validator) target.getValue().get()); + if (target.getValue() != null && target.getValue().get() instanceof Validator validator) { + validators.add(validator); } return validators; } @@ -184,8 +184,8 @@ class ConfigurationPropertiesBinder { } private Consumer getPropertyEditorInitializer() { - if (this.applicationContext instanceof ConfigurableApplicationContext) { - return ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory()::copyRegisteredEditorsTo; + if (this.applicationContext instanceof ConfigurableApplicationContext configurableContext) { + return configurableContext.getBeanFactory()::copyRegisteredEditorsTo; } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java index 1a78498c53..9fb9b5b3af 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConversionServiceDeducer.java @@ -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. @@ -51,8 +51,8 @@ class ConversionServiceDeducer { return Collections.singletonList(this.applicationContext .getBean(ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } - if (this.applicationContext instanceof ConfigurableApplicationContext) { - return getConversionServices((ConfigurableApplicationContext) this.applicationContext); + if (this.applicationContext instanceof ConfigurableApplicationContext configurableContext) { + return getConversionServices(configurableContext); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java index deac5534b1..bc97bfe1d7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertySourcesDeducer.java @@ -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,8 @@ class PropertySourcesDeducer { private MutablePropertySources extractEnvironmentPropertySources() { Environment environment = this.applicationContext.getEnvironment(); - if (environment instanceof ConfigurableEnvironment) { - return ((ConfigurableEnvironment) environment).getPropertySources(); + if (environment instanceof ConfigurableEnvironment configurableEnvironment) { + return configurableEnvironment.getPropertySources(); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java index 0b47cff04e..eb3c9c34f3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java @@ -381,8 +381,8 @@ public class Binder { return context.getConverter().convert(result, target); } catch (Exception ex) { - if (ex instanceof BindException) { - throw (BindException) ex; + if (ex instanceof BindException bindException) { + throw bindException; } throw new BindException(name, target, context.getConfigurationProperty(), ex); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java index 4b8cc94531..96a97c225a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java @@ -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. @@ -116,10 +116,10 @@ abstract class IndexedElementsBinder extends AggregateBinder { private MultiValueMap getKnownIndexedChildren(ConfigurationPropertySource source, ConfigurationPropertyName root) { MultiValueMap children = new LinkedMultiValueMap<>(); - if (!(source instanceof IterableConfigurationPropertySource)) { + if (!(source instanceof IterableConfigurationPropertySource iterableSource)) { return children; } - for (ConfigurationPropertyName name : (IterableConfigurationPropertySource) source.filter(root::isAncestorOf)) { + for (ConfigurationPropertyName name : iterableSource.filter(root::isAncestorOf)) { ConfigurationPropertyName choppedName = name.chop(root.getNumberOfElements() + 1); if (choppedName.isLastElementIndexed()) { String key = choppedName.getLastElement(Form.UNIFORM); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java index e484cf4748..1b30b96829 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java @@ -150,8 +150,8 @@ class MapBinder extends AggregateBinder> { } void bindEntries(ConfigurationPropertySource source, Map map) { - if (source instanceof IterableConfigurationPropertySource) { - for (ConfigurationPropertyName name : (IterableConfigurationPropertySource) source) { + if (source instanceof IterableConfigurationPropertySource iterableSource) { + for (ConfigurationPropertyName name : iterableSource) { Bindable valueBindable = getValueBindable(name); ConfigurationPropertyName entryName = getEntryName(source, name); Object key = getContext().getConverter().convert(getKeyName(entryName), this.keyType); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java index ef0932f450..b6b6b9e10c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java @@ -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. @@ -53,8 +53,8 @@ public class PropertySourcesPlaceholdersResolver implements PlaceholdersResolver @Override public Object resolvePlaceholders(Object value) { - if (value instanceof String) { - return this.helper.replacePlaceholders((String) value, this::resolvePlaceholder); + if (value instanceof String string) { + return this.helper.replacePlaceholders(string, this::resolvePlaceholder); } return value; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java index ab446865b8..6f18d8c611 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java @@ -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. @@ -98,8 +98,8 @@ class ValueObjectBinder implements DataObjectBinder { ResolvableType type = parameter.getType(); Annotation[] annotations = parameter.getAnnotations(); for (Annotation annotation : annotations) { - if (annotation instanceof DefaultValue) { - String[] defaultValue = ((DefaultValue) annotation).value(); + if (annotation instanceof DefaultValue defaultValueAnnotation) { + String[] defaultValue = defaultValueAnnotation.value(); if (defaultValue.length == 0) { return getNewInstanceIfPossible(context, type); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java index 36a101e38f..1dd1d57846 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/validation/ValidationErrors.java @@ -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. @@ -68,8 +68,8 @@ public class ValidationErrors implements Iterable { private ObjectError convertError(ConfigurationPropertyName name, Set boundProperties, ObjectError error) { - if (error instanceof FieldError) { - return convertFieldError(name, boundProperties, (FieldError) error); + if (error instanceof FieldError fieldError) { + return convertFieldError(name, boundProperties, fieldError); } return error; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/CachingConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/CachingConfigurationPropertySource.java index 61b894d815..bc085bf919 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/CachingConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/CachingConfigurationPropertySource.java @@ -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. @@ -37,8 +37,8 @@ interface CachingConfigurationPropertySource { * source does not support caching. */ static ConfigurationPropertyCaching find(ConfigurationPropertySource source) { - if (source instanceof CachingConfigurationPropertySource) { - return ((CachingConfigurationPropertySource) source).getCaching(); + if (source instanceof CachingConfigurationPropertySource cachingSource) { + return cachingSource.getCaching(); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java index 33dfbdada2..0f1501729a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java @@ -158,8 +158,8 @@ public final class ConfigurationPropertySources { } private static Stream> flatten(PropertySource source) { - if (source.getSource() instanceof ConfigurableEnvironment) { - return streamPropertySources(((ConfigurableEnvironment) source.getSource()).getPropertySources()); + if (source.getSource() instanceof ConfigurableEnvironment configurableEnvironment) { + return streamPropertySources(configurableEnvironment.getPropertySources()); } return Stream.of(source); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java index 40c4158ed0..73f491684c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java @@ -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. @@ -75,8 +75,8 @@ class ConfigurationPropertySourcesPropertyResolver extends AbstractPropertyResol if (value == null) { return null; } - if (resolveNestedPlaceholders && value instanceof String) { - value = resolveNestedPlaceholders((String) value); + if (resolveNestedPlaceholders && value instanceof String string) { + value = resolveNestedPlaceholders(string); } return convertValueIfNecessary(value, targetValueType); } @@ -101,8 +101,8 @@ class ConfigurationPropertySourcesPropertyResolver extends AbstractPropertyResol ConfigurationPropertySourcesPropertySource attached = (ConfigurationPropertySourcesPropertySource) ConfigurationPropertySources .getAttached(this.propertySources); Iterable attachedSource = (attached != null) ? attached.getSource() : null; - if ((attachedSource instanceof SpringConfigurationPropertySources) - && ((SpringConfigurationPropertySources) attachedSource).isUsingSources(this.propertySources)) { + if ((attachedSource instanceof SpringConfigurationPropertySources springSource) + && springSource.isUsingSources(this.propertySources)) { return attached; } return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java index 285f06d403..8c683db01d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java @@ -97,11 +97,12 @@ class SpringConfigurationPropertySource implements ConfigurationPropertySource { @Override public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) { PropertySource source = getPropertySource(); - if (source.getSource() instanceof Random) { + Object underlyingSource = source.getSource(); + if (underlyingSource instanceof Random) { return containsDescendantOfForRandom("random", name); } - if (source.getSource() instanceof PropertySource - && ((PropertySource) source.getSource()).getSource() instanceof Random) { + if (underlyingSource instanceof PropertySource underlyingPropertySource + && underlyingPropertySource.getSource() instanceof Random) { // Assume wrapped random sources use the source name as the prefix return containsDescendantOfForRandom(source.getName(), name); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java index c3202f8967..7565143ea1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java @@ -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. @@ -114,8 +114,8 @@ class SpringConfigurationPropertySources implements Iterable candidate = this.iterators.peek().next(); - if (candidate.getSource() instanceof ConfigurableEnvironment) { - push((ConfigurableEnvironment) candidate.getSource()); + if (candidate.getSource() instanceof ConfigurableEnvironment configurableEnvironment) { + push(configurableEnvironment); return fetchNext(); } if (isIgnored(candidate)) { diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java index 60ebbe4059..deb3a22223 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySource.java @@ -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. @@ -77,9 +77,9 @@ class SpringIterableConfigurationPropertySource extends SpringConfigurationPrope } private void assertEnumerablePropertySource() { - if (getPropertySource() instanceof MapPropertySource) { + if (getPropertySource() instanceof MapPropertySource mapSource) { try { - ((MapPropertySource) getPropertySource()).getSource().size(); + mapSource.getSource().size(); } catch (UnsupportedOperationException ex) { throw new IllegalArgumentException("PropertySource must be fully enumerable"); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java index 06f49fe4da..e8cb49dea0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java @@ -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. @@ -230,8 +230,8 @@ public class ApplicationConversionService extends FormattingConversionService { registry.addConverter(new InputStreamSourceToByteArrayConverter()); registry.addConverterFactory(new LenientStringToEnumConverterFactory()); registry.addConverterFactory(new LenientBooleanToEnumConverterFactory()); - if (registry instanceof ConversionService) { - addApplicationConverters(registry, (ConversionService) registry); + if (registry instanceof ConversionService conversionService) { + addApplicationConverters(registry, conversionService); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CharSequenceToObjectConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CharSequenceToObjectConverter.java index cc2b40d400..578e300dbc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CharSequenceToObjectConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/CharSequenceToObjectConverter.java @@ -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. @@ -80,8 +80,7 @@ class CharSequenceToObjectConverter implements ConditionalGenericConverter { * @return if string conversion is better */ private boolean isStringConversionBetter(TypeDescriptor sourceType, TypeDescriptor targetType) { - if (this.conversionService instanceof ApplicationConversionService) { - ApplicationConversionService applicationConversionService = (ApplicationConversionService) this.conversionService; + if (this.conversionService instanceof ApplicationConversionService applicationConversionService) { if (applicationConversionService.isConvertViaObjectSourceType(sourceType, targetType)) { // If an ObjectTo... converter is being used then there might be a better // StringTo... version diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverter.java index bd03e3f43a..f00f637088 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/convert/InputStreamSourceToByteArrayConverter.java @@ -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. @@ -46,8 +46,8 @@ class InputStreamSourceToByteArrayConverter implements Converter { - if (analyzer instanceof BeanFactoryAware) { - ((BeanFactoryAware) analyzer).setBeanFactory(context.getBeanFactory()); + if (analyzer instanceof BeanFactoryAware beanFactoryAware) { + beanFactoryAware.setBeanFactory(context.getBeanFactory()); } - if (analyzer instanceof EnvironmentAware) { - ((EnvironmentAware) analyzer).setEnvironment(context.getEnvironment()); + if (analyzer instanceof EnvironmentAware environmentAware) { + environmentAware.setEnvironment(context.getEnvironment()); } }); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java index 44de27d6cb..81beb18ac3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanCurrentlyInCreationFailureAnalyzer.java @@ -41,8 +41,8 @@ class BeanCurrentlyInCreationFailureAnalyzer extends AbstractFailureAnalyzer { StringBuilder description = new StringBuilder( String.format("Binding to target %s failed:%n", details.getTarget())); for (ObjectError error : details.getErrors()) { - if (error instanceof FieldError) { - appendFieldError(description, (FieldError) error); + if (error instanceof FieldError fieldError) { + appendFieldError(description, fieldError); } description.append(String.format("%n Reason: %s%n", error.getDefaultMessage())); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListener.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListener.java index c478c11b53..cdd020be42 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListener.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/EnvironmentPostProcessorApplicationListener.java @@ -90,8 +90,8 @@ public class EnvironmentPostProcessorApplicationListener implements SmartApplica @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ApplicationEnvironmentPreparedEvent) { - onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event); + if (event instanceof ApplicationEnvironmentPreparedEvent environmentPreparedEvent) { + onApplicationEnvironmentPreparedEvent(environmentPreparedEvent); } if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java index 7e1d5c11c8..5bc8e11f30 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java @@ -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,8 +62,8 @@ public final class OriginTrackedMapPropertySource extends MapPropertySource impl @Override public Object getProperty(String name) { Object value = super.getProperty(name); - if (value instanceof OriginTrackedValue) { - return ((OriginTrackedValue) value).getValue(); + if (value instanceof OriginTrackedValue originTrackedValue) { + return originTrackedValue.getValue(); } return value; } @@ -71,8 +71,8 @@ public final class OriginTrackedMapPropertySource extends MapPropertySource impl @Override public Origin getOrigin(String name) { Object value = super.getProperty(name); - if (value instanceof OriginTrackedValue) { - return ((OriginTrackedValue) value).getOrigin(); + if (value instanceof OriginTrackedValue originTrackedValue) { + return originTrackedValue.getOrigin(); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java index 16861bac0b..472368a487 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedYamlLoader.java @@ -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. @@ -113,8 +113,8 @@ class OriginTrackedYamlLoader extends YamlProcessor { return constructTrackedObject(node, super.constructObject(node)); } } - if (node instanceof MappingNode) { - replaceMappingNodeKeys((MappingNode) node); + if (node instanceof MappingNode mappingNode) { + replaceMappingNodeKeys(mappingNode); } return super.constructObject(node); } @@ -156,8 +156,8 @@ class OriginTrackedYamlLoader extends YamlProcessor { } private static Node get(Node node) { - if (node instanceof ScalarNode) { - return new KeyScalarNode((ScalarNode) node); + if (node instanceof ScalarNode scalarNode) { + return new KeyScalarNode(scalarNode); } return node; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java index 2194403f48..85ff1e636c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java @@ -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. @@ -67,11 +67,11 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar public void registerJsonComponents() { BeanFactory beanFactory = this.beanFactory; while (beanFactory != null) { - if (beanFactory instanceof ListableBeanFactory) { - addJsonBeans((ListableBeanFactory) beanFactory); + if (beanFactory instanceof ListableBeanFactory listableBeanFactory) { + addJsonBeans(listableBeanFactory); } - beanFactory = (beanFactory instanceof HierarchicalBeanFactory) - ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() : null; + beanFactory = (beanFactory instanceof HierarchicalBeanFactory hierarchicalBeanFactory) + ? hierarchicalBeanFactory.getParentBeanFactory() : null; } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java index 9b361ad774..06ce2a12a5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java @@ -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. @@ -50,8 +50,8 @@ public abstract class JsonObjectDeserializer extends com.fasterxml.jackson.da return deserializeObject(jp, ctxt, codec, tree); } catch (Exception ex) { - if (ex instanceof IOException) { - throw (IOException) ex; + if (ex instanceof IOException ioException) { + throw ioException; } throw new JsonMappingException(jp, "Object deserialize error", ex); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java index b4ccf3d8b8..2887da8d68 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java @@ -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. @@ -41,8 +41,8 @@ public abstract class JsonObjectSerializer extends JsonSerializer { jgen.writeEndObject(); } catch (Exception ex) { - if (ex instanceof IOException) { - throw (IOException) ex; + if (ex instanceof IOException ioException) { + throw ioException; } throw new JsonMappingException(jgen, "Object serialize error", ex); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java index a2e2725f67..39c839220a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java @@ -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. @@ -69,8 +69,8 @@ public final class DataSourceUnwrapper { } if (AopUtils.isAopProxy(dataSource)) { Object proxyTarget = AopProxyUtils.getSingletonTarget(dataSource); - if (proxyTarget instanceof DataSource) { - return unwrap((DataSource) proxyTarget, unwrapInterface, target); + if (proxyTarget instanceof DataSource proxyDataSource) { + return unwrap(proxyDataSource, unwrapInterface, target); } } return null; @@ -105,8 +105,8 @@ public final class DataSourceUnwrapper { private static class DelegatingDataSourceUnwrapper { private static DataSource getTargetDataSource(DataSource dataSource) { - if (dataSource instanceof DelegatingDataSource) { - return ((DelegatingDataSource) dataSource).getTargetDataSource(); + if (dataSource instanceof DelegatingDataSource delegatingDataSource) { + return delegatingDataSource.getTargetDataSource(); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java index 81b440ec65..05795a5203 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java @@ -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. @@ -237,8 +237,8 @@ public class DeferredLog implements Log { * @return the destination */ public static Log replay(Log source, Log destination) { - if (source instanceof DeferredLog) { - ((DeferredLog) source).replayTo(destination); + if (source instanceof DeferredLog deferredLog) { + deferredLog.replayTo(destination); } return destination; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java index ba2a6142f2..b36af0743f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java @@ -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. @@ -79,8 +79,7 @@ public final class LoggerConfiguration { if (obj == null) { return false; } - if (obj instanceof LoggerConfiguration) { - LoggerConfiguration other = (LoggerConfiguration) obj; + if (obj instanceof LoggerConfiguration other) { boolean rtn = true; rtn = rtn && ObjectUtils.nullSafeEquals(this.name, other.name); rtn = rtn && ObjectUtils.nullSafeEquals(this.configuredLevel, other.configuredLevel); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java index a74f4638c8..05a6d6e917 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java @@ -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. @@ -149,9 +149,9 @@ public class LoggingSystemProperties { } private PropertyResolver getPropertyResolver() { - if (this.environment instanceof ConfigurableEnvironment) { + if (this.environment instanceof ConfigurableEnvironment configurableEnvironment) { PropertySourcesPropertyResolver resolver = new PropertySourcesPropertyResolver( - ((ConfigurableEnvironment) this.environment).getPropertySources()); + configurableEnvironment.getPropertySources()); resolver.setConversionService(((ConfigurableEnvironment) this.environment).getConversionService()); resolver.setIgnoreUnresolvableNestedPlaceholders(true); return resolver; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java index 7ac194c9d0..c365ffd20e 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java @@ -447,8 +447,8 @@ public class Log4J2LoggingSystem extends AbstractLoggingSystem { private LoggerConfig findLogger(String name) { Configuration configuration = getLoggerContext().getConfiguration(); - if (configuration instanceof AbstractConfiguration) { - return ((AbstractConfiguration) configuration).getLogger(name); + if (configuration instanceof AbstractConfiguration abstractConfiguration) { + return abstractConfiguration.getLogger(name); } return configuration.getLoggers().get(name); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java index 4b8d6b0646..be30cc7ac6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java @@ -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. @@ -102,8 +102,8 @@ class LogbackConfigurator { } void start(LifeCycle lifeCycle) { - if (lifeCycle instanceof ContextAware) { - ((ContextAware) lifeCycle).setContext(this.context); + if (lifeCycle instanceof ContextAware contextAware) { + contextAware.setContext(this.context); } lifeCycle.start(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystemProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystemProperties.java index 8985ac7a6d..74adcd51da 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystemProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackLoggingSystemProperties.java @@ -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. @@ -109,7 +109,7 @@ public class LogbackLoggingSystemProperties extends LoggingSystemProperties { value = getProperty(resolver, deprecatedPropertyName, type); } if (value != null) { - String stringValue = String.valueOf((value instanceof DataSize) ? ((DataSize) value).toBytes() : value); + String stringValue = String.valueOf((value instanceof DataSize dataSize) ? dataSize.toBytes() : value); setSystemProperty(systemPropertyName, stringValue); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/Origin.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/Origin.java index 455638ed4d..680ecfa0b7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/Origin.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/Origin.java @@ -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. @@ -57,15 +57,15 @@ public interface Origin { * @return an optional {@link Origin} */ static Origin from(Object source) { - if (source instanceof Origin) { - return (Origin) source; + if (source instanceof Origin origin) { + return origin; } Origin origin = null; - if (source instanceof OriginProvider) { - origin = ((OriginProvider) source).getOrigin(); + if (source instanceof OriginProvider originProvider) { + origin = originProvider.getOrigin(); } - if (origin == null && source instanceof Throwable) { - return from(((Throwable) source).getCause()); + if (origin == null && source instanceof Throwable throwable) { + return from(throwable.getCause()); } return origin; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedResource.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedResource.java index 8cbb063dc1..e9ea446600 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedResource.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedResource.java @@ -179,8 +179,8 @@ public class OriginTrackedResource implements Resource, OriginProvider { * @return an {@link OriginTrackedResource} instance */ public static OriginTrackedResource of(Resource resource, Origin origin) { - if (resource instanceof WritableResource) { - return new OriginTrackedWritableResource((WritableResource) resource, origin); + if (resource instanceof WritableResource writableResource) { + return new OriginTrackedWritableResource(writableResource, origin); } return new OriginTrackedResource(resource, origin); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java index 5f5d6dd63a..5bc8dd254a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java @@ -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. @@ -86,8 +86,8 @@ public class OriginTrackedValue implements OriginProvider { if (value == null) { return null; } - if (value instanceof CharSequence) { - return new OriginTrackedCharSequence((CharSequence) value, origin); + if (value instanceof CharSequence charSequence) { + return new OriginTrackedCharSequence(charSequence, origin); } return new OriginTrackedValue(value, origin); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java index f4cbffc037..1283dbbf0d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java @@ -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. @@ -73,8 +73,7 @@ public class TextResourceOrigin implements Origin { if (obj == null) { return false; } - if (obj instanceof TextResourceOrigin) { - TextResourceOrigin other = (TextResourceOrigin) obj; + if (obj instanceof TextResourceOrigin other) { boolean result = true; result = result && ObjectUtils.nullSafeEquals(this.resource, other.resource); result = result && ObjectUtils.nullSafeEquals(this.location, other.location); @@ -102,14 +101,14 @@ public class TextResourceOrigin implements Origin { } private String getResourceDescription(Resource resource) { - if (resource instanceof OriginTrackedResource) { - return getResourceDescription(((OriginTrackedResource) resource).getResource()); + if (resource instanceof OriginTrackedResource originTrackedResource) { + return getResourceDescription(originTrackedResource.getResource()); } if (resource == null) { return "unknown resource [?]"; } - if (resource instanceof ClassPathResource) { - return getResourceDescription((ClassPathResource) resource); + if (resource instanceof ClassPathResource classPathResource) { + return getResourceDescription(classPathResource); } return resource.getDescription(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java index 04d583391a..bf6ff65b75 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/r2dbc/ConnectionFactoryBuilder.java @@ -283,8 +283,8 @@ public final class ConnectionFactoryBuilder { if (type.isInstance(object)) { return type.cast(object); } - if (object instanceof String) { - return converter.apply((String) object); + if (object instanceof String string) { + return converter.apply(string); } throw new IllegalArgumentException("Cannot convert '" + object + "' to " + type.getName()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/context/RSocketPortInfoApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/context/RSocketPortInfoApplicationContextInitializer.java index aede35e677..946fa8eec9 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/context/RSocketPortInfoApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/rsocket/context/RSocketPortInfoApplicationContextInitializer.java @@ -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. @@ -69,8 +69,8 @@ public class RSocketPortInfoApplicationContextInitializer } private void setPortProperty(ApplicationContext context, int port) { - if (context instanceof ConfigurableApplicationContext) { - setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), port); + if (context instanceof ConfigurableApplicationContext configurableContext) { + setPortProperty(configurableContext.getEnvironment(), port); } if (context.getParent() != null) { setPortProperty(context.getParent(), port); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java index b86c408ff4..5d41224187 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java @@ -162,8 +162,8 @@ public class DatabaseInitializationDependencyConfigurer implements ImportBeanDef } catch (NoSuchBeanDefinitionException ex) { BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory(); - if (parentBeanFactory instanceof ConfigurableListableBeanFactory) { - return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory); + if (parentBeanFactory instanceof ConfigurableListableBeanFactory configurableBeanFactory) { + return getBeanDefinition(beanName, configurableBeanFactory); } throw ex; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java index 92ba30ab33..cd05e9c023 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java @@ -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. @@ -118,8 +118,8 @@ public class ApplicationHome { private File findSource(URL location) throws IOException, URISyntaxException { URLConnection connection = location.openConnection(); - if (connection instanceof JarURLConnection) { - return getRootJarFile(((JarURLConnection) connection).getJarFile()); + if (connection instanceof JarURLConnection jarURLConnection) { + return getRootJarFile(jarURLConnection.getJarFile()); } return new File(location.toURI()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java index 3054499c66..a5f827bc76 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationPid.java @@ -62,8 +62,8 @@ public class ApplicationPid { if (obj == this) { return true; } - if (obj instanceof ApplicationPid) { - return ObjectUtils.nullSafeEquals(this.pid, ((ApplicationPid) obj).pid); + if (obj instanceof ApplicationPid other) { + return ObjectUtils.nullSafeEquals(this.pid, other.pid); } return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java index 9be31b9d96..45996a39fa 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/system/ApplicationTemp.java @@ -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. @@ -154,8 +154,8 @@ public class ApplicationTemp { } private byte[] getUpdateSourceBytes(Object source) { - if (source instanceof File) { - return getUpdateSourceBytes(((File) source).getAbsolutePath()); + if (source instanceof File file) { + return getUpdateSourceBytes(file.getAbsolutePath()); } return source.toString().getBytes(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java index 3914964b25..c47a2f46a5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/ServerPortInfoApplicationContextInitializer.java @@ -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. @@ -69,8 +69,8 @@ public class ServerPortInfoApplicationContextInitializer implements } private void setPortProperty(ApplicationContext context, String propertyName, int port) { - if (context instanceof ConfigurableApplicationContext) { - setPortProperty(((ConfigurableApplicationContext) context).getEnvironment(), propertyName, port); + if (context instanceof ConfigurableApplicationContext configurableContext) { + setPortProperty(configurableContext.getEnvironment(), propertyName, port); } if (context.getParent() != null) { setPortProperty(context.getParent(), propertyName, port); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerApplicationContext.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerApplicationContext.java index 8d1e660be7..ad5365a614 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerApplicationContext.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerApplicationContext.java @@ -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. @@ -54,8 +54,8 @@ public interface WebServerApplicationContext extends ApplicationContext { * @since 2.1.8 */ static boolean hasServerNamespace(ApplicationContext context, String serverNamespace) { - return (context instanceof WebServerApplicationContext) && ObjectUtils - .nullSafeEquals(((WebServerApplicationContext) context).getServerNamespace(), serverNamespace); + return (context instanceof WebServerApplicationContext webServerApplicationContext) + && ObjectUtils.nullSafeEquals(webServerApplicationContext.getServerNamespace(), serverNamespace); } /** @@ -67,8 +67,8 @@ public interface WebServerApplicationContext extends ApplicationContext { * @since 2.6.0 */ static String getServerNamespace(ApplicationContext context) { - return (context instanceof WebServerApplicationContext) - ? ((WebServerApplicationContext) context).getServerNamespace() : null; + return (context instanceof WebServerApplicationContext configurableContext) + ? configurableContext.getServerNamespace() : null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java index 7b953c1c33..0ec76343eb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/context/WebServerPortFileWriter.java @@ -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. @@ -124,8 +124,8 @@ public class WebServerPortFileWriter implements ApplicationListener errorPages) { - if (errorHandler instanceof ErrorPageErrorHandler) { - ErrorPageErrorHandler handler = (ErrorPageErrorHandler) errorHandler; + if (errorHandler instanceof ErrorPageErrorHandler handler) { for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { handler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, errorPage.getPath()); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java index a6d3356f7c..2433ccc959 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/jetty/JettyWebServer.java @@ -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. @@ -103,11 +103,11 @@ public class JettyWebServer implements WebServer { } private StatisticsHandler findStatisticsHandler(Handler handler) { - if (handler instanceof StatisticsHandler) { - return (StatisticsHandler) handler; + if (handler instanceof StatisticsHandler statisticsHandler) { + return statisticsHandler; } - if (handler instanceof HandlerWrapper) { - return findStatisticsHandler(((HandlerWrapper) handler).getHandler()); + if (handler instanceof HandlerWrapper handlerWrapper) { + return findStatisticsHandler(handlerWrapper.getHandler()); } return null; } @@ -161,9 +161,8 @@ public class JettyWebServer implements WebServer { connector.start(); } catch (IOException ex) { - if (connector instanceof NetworkConnector) { - PortInUseException.throwIfPortBindingException(ex, - () -> ((NetworkConnector) connector).getPort()); + if (connector instanceof NetworkConnector networkConnector) { + PortInUseException.throwIfPortBindingException(ex, networkConnector::getPort); } throw ex; } @@ -205,25 +204,25 @@ public class JettyWebServer implements WebServer { } private ContextHandler findContextHandler(Handler handler) { - while (handler instanceof HandlerWrapper) { - if (handler instanceof ContextHandler) { - return (ContextHandler) handler; + while (handler instanceof HandlerWrapper handlerWrapper) { + if (handler instanceof ContextHandler contextHandler) { + return contextHandler; } - handler = ((HandlerWrapper) handler).getHandler(); + handler = handlerWrapper.getHandler(); } return null; } private void handleDeferredInitialize(Handler... handlers) throws Exception { for (Handler handler : handlers) { - if (handler instanceof JettyEmbeddedWebAppContext) { - ((JettyEmbeddedWebAppContext) handler).deferredInitialize(); + if (handler instanceof JettyEmbeddedWebAppContext jettyEmbeddedWebAppContext) { + jettyEmbeddedWebAppContext.deferredInitialize(); } - else if (handler instanceof HandlerWrapper) { - handleDeferredInitialize(((HandlerWrapper) handler).getHandler()); + else if (handler instanceof HandlerWrapper handlerWrapper) { + handleDeferredInitialize(handlerWrapper.getHandler()); } - else if (handler instanceof HandlerCollection) { - handleDeferredInitialize(((HandlerCollection) handler).getHandlers()); + else if (handler instanceof HandlerCollection handlerCollection) { + handleDeferredInitialize(handlerCollection.getHandlers()); } } } @@ -260,8 +259,8 @@ public class JettyWebServer implements WebServer { } private Integer getLocalPort(Connector connector) { - if (connector instanceof NetworkConnector) { - return ((NetworkConnector) connector).getLocalPort(); + if (connector instanceof NetworkConnector networkConnector) { + return networkConnector.getLocalPort(); } return 0; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java index d5f61419ef..8b555f350f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/netty/NettyWebServer.java @@ -147,11 +147,11 @@ public class NettyWebServer implements WebServer { private boolean isPermissionDenied(Throwable bindExceptionCause) { try { - if (bindExceptionCause instanceof NativeIoException) { - return ((NativeIoException) bindExceptionCause).expectedErr() == ERROR_NO_EACCES; + if (bindExceptionCause instanceof NativeIoException nativeException) { + return nativeException.expectedErr() == ERROR_NO_EACCES; } } - catch (Throwable ex) { + catch (Throwable ignore) { } return false; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/DisableReferenceClearingContextCustomizer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/DisableReferenceClearingContextCustomizer.java index addf1c789e..fa53c784f2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/DisableReferenceClearingContextCustomizer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/DisableReferenceClearingContextCustomizer.java @@ -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. @@ -29,10 +29,9 @@ class DisableReferenceClearingContextCustomizer implements TomcatContextCustomiz @Override public void customize(Context context) { - if (!(context instanceof StandardContext)) { + if (!(context instanceof StandardContext standardContext)) { return; } - StandardContext standardContext = (StandardContext) context; try { standardContext.setClearReferencesObjectStreamClassCaches(false); standardContext.setClearReferencesRmiTargets(false); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java index 2035cef9fb..5d3086143c 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactory.java @@ -371,8 +371,7 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto */ protected void configureContext(Context context, ServletContextInitializer[] initializers) { TomcatStarter starter = new TomcatStarter(initializers); - if (context instanceof TomcatEmbeddedContext) { - TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context; + if (context instanceof TomcatEmbeddedContext embeddedContext) { embeddedContext.setStarter(starter); embeddedContext.setFailCtxIfServletStartFails(true); } @@ -752,8 +751,8 @@ public class TomcatServletWebServerFactory extends AbstractServletWebServerFacto if (event.getType().equals(Lifecycle.START_EVENT)) { Context context = (Context) event.getLifecycle(); Manager manager = context.getManager(); - if (manager instanceof StandardManager) { - ((StandardManager) manager).setPathname(null); + if (manager instanceof StandardManager standardManager) { + standardManager.setPathname(null); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java index 25c260c4f0..6b910671c8 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatWebServer.java @@ -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. @@ -146,8 +146,8 @@ public class TomcatWebServer implements WebServer { private Context findContext() { for (Container child : this.tomcat.getHost().findChildren()) { - if (child instanceof Context) { - return (Context) child; + if (child instanceof Context context) { + return context; } } throw new IllegalStateException("The host does not contain a Context"); @@ -174,8 +174,8 @@ public class TomcatWebServer implements WebServer { private void rethrowDeferredStartupExceptions() throws Exception { Container[] children = this.tomcat.getHost().findChildren(); for (Container container : children) { - if (container instanceof TomcatEmbeddedContext) { - TomcatStarter tomcatStarter = ((TomcatEmbeddedContext) container).getStarter(); + if (container instanceof TomcatEmbeddedContext embeddedContext) { + TomcatStarter tomcatStarter = embeddedContext.getStarter(); if (tomcatStarter != null) { Exception exception = tomcatStarter.getStartUpException(); if (exception != null) { @@ -301,14 +301,14 @@ public class TomcatWebServer implements WebServer { private void performDeferredLoadOnStartup() { try { for (Container child : this.tomcat.getHost().findChildren()) { - if (child instanceof TomcatEmbeddedContext) { - ((TomcatEmbeddedContext) child).deferredLoadOnStartup(); + if (child instanceof TomcatEmbeddedContext embeddedContext) { + embeddedContext.deferredLoadOnStartup(); } } } catch (Exception ex) { - if (ex instanceof WebServerException) { - throw (WebServerException) ex; + if (ex instanceof WebServerException webServerException) { + throw webServerException; } throw new WebServerException("Unable to start embedded Tomcat connectors", ex); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java index dca13a3eb3..11ce72755b 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServer.java @@ -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. @@ -60,8 +60,8 @@ public class UndertowServletWebServer extends UndertowWebServer { private DeploymentManager findManager(Iterable httpHandlerFactories) { for (HttpHandlerFactory httpHandlerFactory : httpHandlerFactories) { - if (httpHandlerFactory instanceof DeploymentManagerHttpHandlerFactory) { - return ((DeploymentManagerHttpHandlerFactory) httpHandlerFactory).getDeploymentManager(); + if (httpHandlerFactory instanceof DeploymentManagerHttpHandlerFactory deploymentManagerFactory) { + return deploymentManagerFactory.getDeploymentManager(); } } return null; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index 4650522c5c..87151175c2 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -327,8 +327,8 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac addLocaleMappings(deployment); DeploymentManager manager = Servlets.newContainer().addDeployment(deployment); manager.deploy(); - if (manager.getDeployment() instanceof DeploymentImpl) { - removeSuperfluousMimeMappings((DeploymentImpl) manager.getDeployment(), deployment); + if (manager.getDeployment() instanceof DeploymentImpl managerDeployment) { + removeSuperfluousMimeMappings(managerDeployment, deployment); } SessionManager sessionManager = manager.getDeployment().getSessionManager(); Duration timeoutDuration = getSession().getTimeout(); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java index 06baea42b5..a75fd71378 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowWebServer.java @@ -168,12 +168,12 @@ public class UndertowWebServer implements WebServer { HttpHandler handler = null; for (HttpHandlerFactory factory : this.httpHandlerFactories) { handler = factory.getHandler(handler); - if (handler instanceof Closeable) { - this.closeables.add((Closeable) handler); + if (handler instanceof Closeable closeable) { + this.closeables.add(closeable); } - if (handler instanceof GracefulShutdownHandler) { + if (handler instanceof GracefulShutdownHandler shutdownHandler) { Assert.isNull(this.gracefulShutdown, "Only a single GracefulShutdownHandler can be defined"); - this.gracefulShutdown = (GracefulShutdownHandler) handler; + this.gracefulShutdown = shutdownHandler; } } return handler; @@ -214,10 +214,10 @@ public class UndertowWebServer implements WebServer { private UndertowWebServer.Port getPortFromChannel(BoundChannel channel) { SocketAddress socketAddress = channel.getLocalAddress(); - if (socketAddress instanceof InetSocketAddress) { + if (socketAddress instanceof InetSocketAddress inetSocketAddress) { Field sslField = ReflectionUtils.findField(channel.getClass(), "ssl"); String protocol = (sslField != null) ? "https" : "http"; - return new UndertowWebServer.Port(((InetSocketAddress) socketAddress).getPort(), protocol); + return new UndertowWebServer.Port(inetSocketAddress.getPort(), protocol); } return null; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java index f821882ddd..95cc55a532 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributes.java @@ -99,8 +99,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { } private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation responseStatusAnnotation) { - if (error instanceof ResponseStatusException) { - HttpStatus httpStatus = HttpStatus.resolve(((ResponseStatusException) error).getStatusCode().value()); + if (error instanceof ResponseStatusException responseStatusException) { + HttpStatus httpStatus = HttpStatus.resolve(responseStatusException.getStatusCode().value()); if (httpStatus != null) { return httpStatus; } @@ -112,8 +112,8 @@ public class DefaultErrorAttributes implements ErrorAttributes { if (error instanceof BindingResult) { return error.getMessage(); } - if (error instanceof ResponseStatusException) { - return ((ResponseStatusException) error).getReason(); + if (error instanceof ResponseStatusException responseStatusException) { + return responseStatusException.getReason(); } String reason = responseStatusAnnotation.getValue("reason", String.class).orElse(""); if (StringUtils.hasText(reason)) { @@ -141,8 +141,7 @@ public class DefaultErrorAttributes implements ErrorAttributes { if (includeStackTrace) { addStackTrace(errorAttributes, error); } - if (error instanceof BindingResult) { - BindingResult result = (BindingResult) error; + if (error instanceof BindingResult result) { if (result.hasErrors()) { errorAttributes.put("errors", result.getAllErrors()); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java index 016bdc319c..2971c5d208 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPage.java @@ -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. @@ -112,8 +112,7 @@ public class ErrorPage { if (obj == null) { return false; } - if (obj instanceof ErrorPage) { - ErrorPage other = (ErrorPage) obj; + if (obj instanceof ErrorPage other) { return ObjectUtils.nullSafeEquals(getExceptionName(), other.getExceptionName()) && ObjectUtils.nullSafeEquals(this.path, other.path) && this.status == other.status; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java index 0e25bf2cca..7b2beef2e5 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/ErrorPageRegistrarBeanPostProcessor.java @@ -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. @@ -52,8 +52,8 @@ public class ErrorPageRegistrarBeanPostProcessor implements BeanPostProcessor, B @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof ErrorPageRegistry) { - postProcessBeforeInitialization((ErrorPageRegistry) bean); + if (bean instanceof ErrorPageRegistry errorPageRegistry) { + postProcessBeforeInitialization(errorPageRegistry); } return bean; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java index eda975577a..33928044ef 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java @@ -310,8 +310,7 @@ public final class MimeMappings implements Iterable { if (obj == this) { return true; } - if (obj instanceof MimeMappings) { - MimeMappings other = (MimeMappings) obj; + if (obj instanceof MimeMappings other) { return this.map.equals(other.map); } return false; @@ -364,8 +363,7 @@ public final class MimeMappings implements Iterable { if (obj == this) { return true; } - if (obj instanceof Mapping) { - Mapping other = (Mapping) obj; + if (obj instanceof Mapping other) { return this.extension.equals(other.extension) && this.mimeType.equals(other.mimeType); } return false; diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java index 61c1deb25e..088813c12f 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java @@ -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. @@ -54,8 +54,8 @@ public class WebServerFactoryCustomizerBeanPostProcessor implements BeanPostProc @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof WebServerFactory) { - postProcessBeforeInitialization((WebServerFactory) bean); + if (bean instanceof WebServerFactory webServerFactory) { + postProcessBeforeInitialization(webServerFactory); } return bean; } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java index f0135da429..986bf5d3d0 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletComponentRegisteringPostProcessor.java @@ -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,10 +72,9 @@ class ServletComponentRegisteringPostProcessor implements BeanFactoryPostProcess private void scanPackage(ClassPathScanningCandidateComponentProvider componentProvider, String packageToScan) { for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageToScan)) { - if (candidate instanceof AnnotatedBeanDefinition) { + if (candidate instanceof AnnotatedBeanDefinition annotatedBeanDefinition) { for (ServletComponentHandler handler : HANDLERS) { - handler.handle(((AnnotatedBeanDefinition) candidate), - (BeanDefinitionRegistry) this.applicationContext); + handler.handle(annotatedBeanDefinition, (BeanDefinitionRegistry) this.applicationContext); } } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java index c8c3811816..04e44a0952 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java @@ -140,8 +140,7 @@ public class ServletContextInitializerBeans extends AbstractCollection getUrls() { ClassLoader classLoader = getClass().getClassLoader(); - if (classLoader instanceof URLClassLoader) { - return getUrlsFrom(((URLClassLoader) classLoader).getURLs()); + if (classLoader instanceof URLClassLoader urlClassLoader) { + return getUrlsFrom(urlClassLoader.getURLs()); } else { return getUrlsFrom(Stream.of(ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java index 48c38315f6..a4a4d813c4 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java @@ -132,8 +132,8 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry, Ordered { } catch (Throwable ex) { Throwable exceptionToHandle = ex; - if (ex instanceof ServletException) { - Throwable rootCause = ((ServletException) ex).getRootCause(); + if (ex instanceof ServletException servletException) { + Throwable rootCause = servletException.getRootCause(); if (rootCause != null) { exceptionToHandle = rootCause; } @@ -260,17 +260,17 @@ public class ErrorPageFilter implements Filter, ErrorPageRegistry, Ordered { } private void rethrow(Throwable ex) throws IOException, ServletException { - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; + if (ex instanceof RuntimeException runtimeException) { + throw runtimeException; } - if (ex instanceof Error) { - throw (Error) ex; + if (ex instanceof Error error) { + throw error; } - if (ex instanceof IOException) { - throw (IOException) ex; + if (ex instanceof IOException ioException) { + throw ioException; } - if (ex instanceof ServletException) { - throw (ServletException) ex; + if (ex instanceof ServletException servletException) { + throw servletException; } throw new IllegalStateException(ex); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java index 7b0e097aa2..328e213f48 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java @@ -176,8 +176,8 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit private ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) { Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - if (context instanceof ApplicationContext) { - return (ApplicationContext) context; + if (context instanceof ApplicationContext applicationContext) { + return applicationContext; } return null; } @@ -211,8 +211,8 @@ public abstract class SpringBootServletInitializer implements WebApplicationInit @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); - if (environment instanceof ConfigurableWebEnvironment) { - ((ConfigurableWebEnvironment) environment).initPropertySources(this.servletContext, null); + if (environment instanceof ConfigurableWebEnvironment configurableWebEnvironment) { + configurableWebEnvironment.initPropertySources(this.servletContext, null); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java index a91e5d0332..9fbfbcb1c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/builder/SpringApplicationBuilderTests.java @@ -64,8 +64,8 @@ class SpringApplicationBuilderTests { private void close(ApplicationContext context) { if (context != null) { - if (context instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) context).close(); + if (context instanceof ConfigurableApplicationContext configurableContext) { + configurableContext.close(); } close(context.getParent()); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java index 66e2ee3590..7482cd4a83 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessorTests.java @@ -122,8 +122,8 @@ class ConfigDataEnvironmentPostProcessorTests { } private boolean hasDevProfile(ConfigDataResource resource) { - return (resource instanceof StandardConfigDataResource) - && "dev".equals(((StandardConfigDataResource) resource).getProfile()); + return (resource instanceof StandardConfigDataResource standardResource) + && "dev".equals(standardResource.getProfile()); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java index 502da7408c..90c29e18a0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/ConversionServiceArguments.java @@ -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. @@ -58,8 +58,8 @@ final class ConversionServiceArguments { } static boolean isApplicationConversionService(ConversionService conversionService) { - if (conversionService instanceof NamedConversionService) { - return isApplicationConversionService(((NamedConversionService) conversionService).delegate); + if (conversionService instanceof NamedConversionService namedConversionService) { + return isApplicationConversionService(namedConversionService.delegate); } return conversionService instanceof ApplicationConversionService; } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAge.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAge.java index 7935b13723..789b932c26 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAge.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/NameAndAge.java @@ -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,7 @@ public final class NameAndAge extends Name { if (obj == null) { return false; } - if (obj instanceof NameAndAge) { - NameAndAge other = (NameAndAge) obj; + if (obj instanceof NameAndAge other) { boolean rtn = true; rtn = rtn && ObjectUtils.nullSafeEquals(this.name, other.name); rtn = rtn && ObjectUtils.nullSafeEquals(this.age, other.age); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java index 345c58e1ae..d12e2cb73b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceBuilderTests.java @@ -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. @@ -62,8 +62,8 @@ class DataSourceBuilderTests { @AfterEach void shutdownDataSource() throws IOException { - if (this.dataSource instanceof Closeable) { - ((Closeable) this.dataSource).close(); + if (this.dataSource instanceof Closeable closeable) { + closeable.close(); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index 8973b0c5ae..c199c6936b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -521,11 +521,11 @@ class JettyServletWebServerFactoryTests extends AbstractServletWebServerFactoryT } private WebAppContext findWebAppContext(Handler handler) { - if (handler instanceof WebAppContext) { - return (WebAppContext) handler; + if (handler instanceof WebAppContext webAppContext) { + return webAppContext; } - if (handler instanceof HandlerWrapper) { - return findWebAppContext(((HandlerWrapper) handler).getHandler()); + if (handler instanceof HandlerWrapper wrapper) { + return findWebAppContext(wrapper.getHandler()); } throw new IllegalStateException("No WebAppContext found"); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index 926bfe5fe3..ab5a319cf9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -476,8 +476,8 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsTrue() { TomcatServletWebServerFactory factory = getFactory(); factory.addContextCustomizers((context) -> { - if (context instanceof StandardContext) { - ((StandardContext) context).setFailCtxIfServletStartFails(true); + if (context instanceof StandardContext standardContext) { + standardContext.setFailCtxIfServletStartFails(true); } }); this.webServer = factory @@ -489,8 +489,8 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory void exceptionThrownOnLoadFailureWhenFailCtxIfServletStartFailsIsFalse() { TomcatServletWebServerFactory factory = getFactory(); factory.addContextCustomizers((context) -> { - if (context instanceof StandardContext) { - ((StandardContext) context).setFailCtxIfServletStartFails(false); + if (context instanceof StandardContext standardContext) { + standardContext.setFailCtxIfServletStartFails(false); } }); this.webServer = factory @@ -627,8 +627,8 @@ class TomcatServletWebServerFactoryTests extends AbstractServletWebServerFactory return result; }, (result) -> result instanceof Exception); assertThat(idleConnectionRequestResult).isInstanceOfAny(SocketException.class, NoHttpResponseException.class); - if (idleConnectionRequestResult instanceof SocketException) { - assertThat((SocketException) idleConnectionRequestResult).hasMessage("Connection reset"); + if (idleConnectionRequestResult instanceof SocketException socketException) { + assertThat(socketException).hasMessage("Connection reset"); } blockingServlet.admitOne(); Object response = request.get(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java index d09e94e246..73c96e8833 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/context/AnnotationConfigReactiveWebServerApplicationContextTests.java @@ -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. @@ -93,8 +93,8 @@ class AnnotationConfigReactiveWebServerApplicationContextTests { MockReactiveWebServerFactory factory = this.context.getBean(MockReactiveWebServerFactory.class); HttpHandler expectedHandler = this.context.getBean(HttpHandler.class); HttpHandler actualHandler = factory.getWebServer().getHttpHandler(); - if (actualHandler instanceof DelayedInitializationHttpHandler) { - actualHandler = ((DelayedInitializationHttpHandler) actualHandler).getHandler(); + if (actualHandler instanceof DelayedInitializationHttpHandler delayedHandler) { + actualHandler = delayedHandler.getHandler(); } assertThat(actualHandler).isEqualTo(expectedHandler); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java index e15953a995..facea61e34 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java @@ -657,8 +657,7 @@ public abstract class AbstractReactiveWebServerFactoryTests { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { - if (msg instanceof HttpResponse) { - HttpResponse response = (HttpResponse) msg; + if (msg instanceof HttpResponse response) { boolean compressed = response.headers().contains(HttpHeaderNames.CONTENT_ENCODING, "gzip", true); if (compressed) { response.headers().set("X-Test-Compressed", "true"); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java index 426512ffe6..2596fd6edc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java @@ -487,8 +487,8 @@ class ServletWebServerApplicationContextTests { } static T getBean(T object) { - if (object instanceof RuntimeException) { - throw (RuntimeException) object; + if (object instanceof RuntimeException runtimeException) { + throw runtimeException; } return object; }